带有可变参数的新Function()

mte*_*lis 29 javascript

我需要使用new Function()构造函数创建一个具有可变数量参数的函数.像这样的东西:

args = ['a', 'b'];
body = 'return(a + b);';

myFunc = new Function(args, body);
Run Code Online (Sandbox Code Playgroud)

没有可能eval()吗?


非常感谢你们!实际上,a + b不是我主要关注的问题.我正在研究一个处理和扩展模板的代码,我需要将未知(和变量)数量的参数传递给函数,以便将它们作为局部变量引入.

例如,如果模板包含:

<span> =a </span> 
Run Code Online (Sandbox Code Playgroud)

我需要输出参数的值a.也就是说,如果用户声明扩展功能为

var expand = tplCompile('template', a, b, c) 
Run Code Online (Sandbox Code Playgroud)

然后打电话

expand(4, 2, 1) 
Run Code Online (Sandbox Code Playgroud)

我需要替换=a使用4.是的,我很清楚功能类似于eval()并且运行速度非常慢,但我没有任何其他选择.

And*_*y E 46

你可以使用apply()来做到这一点:

args = ['a', 'b', 'return(a + b);'];
myFunc = Function.apply(null, args);
Run Code Online (Sandbox Code Playgroud)

没有new运算符,Function给出完全相同的结果.您可以使用诸如push(),unshift()splice()之类的数组函数来修改数组,然后再将其传递给apply.

您也可以将逗号分隔的参数字符串传递给Function:

args = 'a, b';
body = 'return(a + b);';

myFunc = new Function(args, body);
Run Code Online (Sandbox Code Playgroud)

另外,您是否知道参数对象?它允许您使用数组样式括号表示法获取传递给函数的所有参数:

myFunc = function () {
    var total = 0;

    for (var i=0; i < arguments.length; i++)
        total += arguments[i];

    return total;
}

myFunc(a, b);
Run Code Online (Sandbox Code Playgroud)

这比使用Function构造函数更有效,并且可能是实现所需内容的更合适的方法.


Tha*_*you 7

如果构造函数不关心你是否使用new关键字,@ AndyE的答案是正确的.有些功能并不宽容.

如果您发现自己处于需要使用new关键字的情况,并且需要向函数发送可变数量的参数,则可以使用此

function Foo() {
  this.numbers = [].slice.apply(arguments);
};


var args = [1,2,3,4,5]; // however many you want
var f = Object.create(Foo.prototype);
Foo.apply(f, args);

f.numbers;          // [1,2,3,4,5]
f instanceof Foo;   // true
f.constructor.name; // "Foo"
Run Code Online (Sandbox Code Playgroud)

ES6及更高版本!

// yup, that easy
function Foo (...numbers) {
  this.numbers = numbers
}

// use Reflect.construct to call Foo constructor
const f =
  Reflect.construct (Foo, [1, 2, 3, 4, 5])

// everything else works
console.log (f.numbers)          // [1,2,3,4,5]
console.log (f instanceof Foo)   // true
console.log (f.constructor.name) // "Foo"
Run Code Online (Sandbox Code Playgroud)


小智 6

你可以这样做:

let args = '...args'
let body = 'let [a, b] = args;return a + b'

myFunc = new Function(args, body);
console.log(myFunc(1, 2)) //3
Run Code Online (Sandbox Code Playgroud)