带有可变参数的新Function() [英] new Function() with variable parameters
问题描述
我需要使用 new Function()
构造函数创建一个具有可变数量参数的函数。这样的事情:
I need to create a function with variable number of parameters using new Function()
constructor. Something like this:
args = ['a', 'b'];
body = 'return(a + b);';
myFunc = new Function(args, body);
是否可以在没有 eval()$ c $的情况下完成c>?
非常感谢,伙计们!实际上,a + b不是我主要关注的问题。我正在研究一个处理和扩展模板的代码,我需要将未知(和变量)数量的参数传递给函数,以便将它们作为局部变量引入。
Thank you very much, guys! Actually, a+b was not my primary concern. I'm working on a code which would process and expand templates and I needed to pass unknown (and variable) number of arguments into the function so that they would be introduced as local variables.
例如,如果模板包含:
<span> =a </span>
我需要输出参数的值
。也就是说,如果用户声明扩展功能为
I need to output the value of parameter a
. That is, if user declared expanding function as
var expand = tplCompile('template', a, b, c)
然后调用
expand(4, 2, 1)
我需要替换 = a
, 4
。是的,我很清楚功能类似于 eval()
并且运行速度非常慢但我没有其他选择。
I need to substitute =a
with 4
. And yes, I'm well aware than Function is similar to eval()
and runs very slow but I don't have any other choice.
推荐答案
您可以使用 apply() :
You can do this using apply():
args = ['a', 'b', 'return(a + b);'];
myFunc = Function.apply(null, args);
没有新
运算符,函数
给出完全相同的结果。您可以使用 push ()<等数组函数/ a>, unshift() 或 splice() 在将数组传递给apply之前修改数组。
Without the new
operator, Function
gives exactly the same result. You can use array functions like push(), unshift() or splice() to modify the array before passing it to apply.
您也可以将逗号分隔的参数字符串传递给 Function :
You can also just pass a comma-separated string of arguments to Function:
args = 'a, b';
body = 'return(a + b);';
myFunc = new Function(args, body);
在旁注中,您是否知道 参数 对象?它允许您使用数组样式括号表示法获取传递给函数的所有参数:
On a side note, are you aware of the arguments object? It allows you to get all the arguments passed into a function using array-style bracket notation:
myFunc = function () {
var total = 0;
for (var i=0; i < arguments.length; i++)
total += arguments[i];
return total;
}
myFunc(a, b);
这比使用 Function 构造函数更有效,可能一种更合适的方法来实现你所需要的。
This would be more efficient than using the Function constructor, and is probably a much more appropriate method of achieving what you need.
这篇关于带有可变参数的新Function()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!