See the following closure problem
var x=10;
function fn() {
console.log(x);
}
function show(f) {
var x=20;
(function() {
f();
})();
}
show(fn);
The print is 10 instead of 20. When x is getting the value, isn’t it looking up along the scope chain? If the scope chain is determined when the function is created, the result will be 10. If it is determined when the function is called, it should be 20. , is there any accurate statement about scope chain? What should the exact scope chain look like here? Are fn and show at the same level or is fn within show?
The scope chain is determined when the function is defined.
https://developer.mozilla.org...
The scope chain is dynamic, so it is determined at call time.
But in your code, the function() defined by the closure is the outermost scope of the binding
The function declared by function defaults to the outermost scope of the binding
(I am also learning...)
Create a scope chain containing global variable objects when the function is created, and store it in the internal [[Scope]] attribute. When the function is executed, an execution environment will be created. By copying the objects in the [[Scope]] attribute, the scope chain of the execution environment will be built, and its own active objects will be pushed into the front end of the scope chain to form a complete function. domain chain. [[Scope]] holds a reference to the global variable, not a copy of the value.
The calling method of closure is equivalent to the following effect. The example given below illustrates through comparison that the scope chain is related to the position when the function is defined.
Relevant question links added. /q/10…. There is a discussion about scope chains.
In non-strict mode, the this point of any IIFE is window
The above is not correct. . .