简体   繁体   中英

Dynamically create a function with default parameters in JavaScript

One of the features introduced by ECMAScript 6 is the ability to indicate default values for unspecified parameters in JavaScript, eg

function foo(a = 2, b = 3) {
    return a * b;
}

console.log(foo());   // 6
console.log(foo(5));  // 15

Now I'm wondering if it's possible to use default parameters also for functions created dynamically with the Function constructor, like this:

new Function('a = 2', 'b = 3', 'return a * b;');

Firefox 39 seems to already support default parameters ( see here ), but the line above is rejected as a syntax error.

Now I'm wondering if it's possible to use default parameters also for functions created dynamically with the Function constructor

Yes, according to the spec this is possible. The parameter arguments are concatenated as always and then parsed according to the FormalParameters production, which includes default values.

Firefox 39 seems to already support default parameters, but the line above is rejected as a syntax error.

Well, that's a bug :-) (probably this one )
You should be able to work around it by using

var fn = Function('return function(a = 2, b = 3) { return a * b; }')();

由于new Function是eval的一种形式,您可以使用以下代码执行该任务:

eval('function bar (a = 2, b = 3) { return a * b; }');

I do not know if that is supposed to work - some one else will have to tell you - but if it continues to be a problem, why not use eval()?

Something in the lines on this should be legal:

var fct1 = eval("(function foo(a = 2, b = 3) { return a * b; })")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM