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?
欧阳克2017-07-05 10:44:15
The scope chain is determined when the function is defined.
Variables defined within a function cannot be accessed anywhere outside the function, because the variables are only defined inside the domain of the function. Correspondingly, a function can access any variables and functions defined within its scope. In other words, a function defined in the global scope can access all variables defined in the global scope. A function defined within another function can also access all variables defined in its parent function and any other variables that the parent function has access to.
https://developer.mozilla.org...
習慣沉默2017-07-05 10:44:15
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...)
PHP中文网2017-07-05 10:44:15
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.
var a = 10;
function f(){
console.log(a);
};
function foo(){
a = 20;
f();
};
foo() // 20;
阿神2017-07-05 10:44:15
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.
var x=10;
function fn(){
console.log(x);
}
function show() {
var x=20;
fn();
}
show(); //输出10
-----------------------
var x=10;
function show() {
var x=20;
function fn(){
console.log(x);
}
fn();
}
show(); //输出20
Relevant question links added. /q/10…. There is a discussion about scope chains.
扔个三星炸死你2017-07-05 10:44:15
In non-strict mode, the this point of any IIFE is window
The above is not correct. . .