Refer to the article
http://suo.im/5L3v4k http://suo.im/60LVo7
Before introducing JavaScript scope chains, let me introduce some of the concepts associated with them
Lexical scope
As we all know, scopes are the visibility and accessibility of variables only, and JavaScript uses lexical scopes.
❝
The lexical scope is determined by where you write the variable and block scopes when you write code.
❞
Ex. :
let number = 42;
function printNumber() {
console.log(number);
}
function test() {
let number = 54;
printNumber();
}
test(); / / 42
Copy the code
As you can see, the printed value is 42, not 54, and the result is determined by where the printNumber is written.
2 Type of scope
2.1 Global scope
Variables in a global scope can be accessed anywhere in the program
Ex. :
var say = 'Hello';
function greet() {
console.log(say);
}
greet(); // Hello
Copy the code
2.2 Local scope or function scope
Variables declared inside a function can only be accessed inside the function, not outside the function
Ex. :
function greet() {
var say = 'Hello';
console.log(say);
}
greet();// Hello
console.log(say); // Uncaught ReferenceError: say is not defined
Copy the code
2.3 Block-level scope
ES6 introduces let,const variables (unlike var, which have no block-level scope) whose scope is the nearest pair of curly braces. They cannot be accessed outside curly braces.
Ex. :
{
let say = 'Hello';
var haha = 'hahaha';
console.log(say); // Hello
}
console.log(haha); // hahaha
console.log(say); // Uncaught ReferenceError: say is not defined
Copy the code
Scope chain
❝
When the current JS engine cannot find a variable to reference in its current scope, the JS engine looks for it in its outer scope until it finds one. If it cannot be found, a reference error is reported
❞
Ex. :
let a = 'a';
function bar() {
let b = 'b';
console.log(b); // b
console.log(a); // a
c = 'c';
console.log(c); // c
}
bar();
Copy the code
- When the bar function is initialized, a private property [[scope]] is maintained for the bar function, which is initialized using the scope chain of the current environment, in this case bar.[[scope]] = global scope;
- When the bar function is executed, the scope chain of the bar is constructed, bar.scopechain = [test.[[scope]]
- Initialize bar’s active object, i.e. Bar.activationobject = [arguments], and the active object is initialized as a variable object, The bar. VariableObject = bar. ActivationObject. Concat [b];
- Bar.scopechain = [test.variableObject, test.[[scope]];