Some problems with default function parameters?
See this
let foo = 'outer';
function bar(func = x => foo) {
let foo = 'inner';
console.log(func());
}
bar(); //outer
I want to know why the output is "external" and not "internal". I know JavaScript has lexical coverage. This output makes me feel like a function x => foo
is being defined from a functionbar
+3
source to share
1 answer
I know js has lexical scope, this output makes me feel like a function
x => foo
is being defined from a functionbar
Not really. It's inside: in a parameter declaration that has its own scope with access to other parameters, but not to the body. The default initializer is basically desugars for
let foo = 'outer';
function bar() {
var func = arguments[0] === undefined ? x => foo : arguments[0];
{
let foo = 'inner';
console.log(func());
}
}
bar(); // outer
0
source to share