Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, e.g.

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.

like image 409
GOTO 0 Avatar asked Nov 09 '22 09:11

GOTO 0


1 Answers

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; }')();
like image 105
Bergi Avatar answered Nov 14 '22 21:11

Bergi