I have a lot of confusion about the situation where the default value of a function parameter is a function
For example
let foo = 'outer';
function bar(func = x => foo) {
let foo = 'inner';
console.log(func());
}
bar(); //outer
According to Ruan Yifeng's es6 introduction, I know that if the function parameters are default values, there will be a block-level scope wrapping the parameters first, and the block-level scope will disappear after the initialization is completed
Once the default value of the parameter is set, the parameter will form a separate scope (context) when the function is declared and initialized. When the initialization is completed, this scope will disappear. This syntax behavior will not appear when the parameter default value is not set.
I can understand if the default value is a normal variable, but I still don’t understand why the output here is outer instead of inner
One sentence: The closure of a function is formed when it is defined, not when it is run.
Expand the syntactic sugar thoroughly and you should be able to see it more clearly
Look,
fk_compiler
can only returnfoo
in the external scope?js is a lexical scope, and the value of foo takes the value when the function is defined rather than when it is executed.
Based on respondent code:
fk_compiler
is declared in the global scope, so it will accessfoo
in the global scope. The answer will come out.Similar code: