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
曾经蜡笔没有小新2017-07-05 11:11:13
One sentence: The closure of a function is formed when it is defined, not when it is run.
给我你的怀抱2017-07-05 11:11:13
Expand the syntactic sugar thoroughly and you should be able to see it more clearly
let foo = 'outer';
function fk_compiler() {
return foo;
}
function bar(func) {
if (func === undefined) {
func = fk_compiler;
}
let foo = 'inner';
console.log(func());
}
bar();
Look, fk_compiler
can only return foo
in the external scope?
習慣沉默2017-07-05 11:11:13
js is a lexical scope, and the value of foo takes the value when the function is defined rather than when it is executed.
给我你的怀抱2017-07-05 11:11:13
Based on respondent code:
let foo = 'outer';
function fk_compiler() {
return foo;
}
function bar(func) {
if (func === undefined) {
func = fk_compiler;
}
let foo = 'inner';
console.log(func());
}
bar();
js adopts lexical scope, so no matter where the function is called, or in any form, its lexical scope is only determined by the position when it is declared.
fk_compiler
is declared in the global scope, so it will access foo
in the global scope. The answer will come out.
Similar code:
function foo(){
console.log(this.a);
}
(function init(){
var a = 'inner';//此处改为 window.a = 'global';再试试
foo();
})();