JavaScript函数是否可以将自己的函数调用作为字符串返回? [英] Is it possible for a JavaScript function to return its own function call as a string?
本文介绍了JavaScript函数是否可以将自己的函数调用作为字符串返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在JavaScript中,函数是否有可能以字符串形式返回其自身的函数调用?
In JavaScript, is it possible for a function to return its own function call as a string?
function getOwnFunctionCall(){
//return the function call as a string, based on the parameters that are given to the function.
}
我希望此函数简单地以字符串形式返回其自身的函数调用(如果可能的话):
I want this function to simply return its own function call as a string (if it's even possible to do this):
var theString = getOwnFunctionCall(5, "3", /(a|b|c)/);
//This function call should simply return the string "getOwnFunctionCall(5, \"3\", "\/(a|b|c)\/")".
推荐答案
我将其放在jsFiddle上: http://jsfiddle.net/pGXgh/.
I put this one up on jsFiddle: http://jsfiddle.net/pGXgh/.
function getOwnFunctionCall() {
var result = "getOwnFunctionCall(";
for (var i=0; i < arguments.length; i++) {
var isString = (toString.call(arguments[i]) == '[object String]');
var quote = (isString) ? "\"" : "";
result += ((i > 0) ? ", " : "");
result += (quote + arguments[i] + quote);
}
return result + ")";
}
alert(getOwnFunctionCall(5, "3", /(a|b|c)/));
请注意,这适用于您的示例,但仍需要处理作为参数包含的任意复杂的对象/JSON.
Note that this should work for your example, but still needs work for arbitrarily complex objects/JSON included as a parameter.
这篇关于JavaScript函数是否可以将自己的函数调用作为字符串返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文