Deep understanding of JavaScript scope and scope chain

1, Scope
(1) What is the scope
Before understanding the scope, first look at the variables and functions. Variables and functions have certain access rights, that is, they must meet the conditions or be within a certain range, which is the scope.

Its concrete manifestation is a specific code, in which the variables and functions are closed and independent, so that the variables will not leak or pollute.

var cat = 'Some fish';
function Person(){
    var name = 'Zhang San';
    console.log(name);//Zhang San, inside the function, in the same scope as the variable name
}
console.log(cat);//Some fish
console.log(name);//There is no result, because name is independent within the function and cannot be accessed


(2) Scope classification
There are three kinds of scopes: global scope, function scope and block scope. Block scope is newly added in ES6, and function scope and block scope are collectively called local scope.
global scope
The variables and functions at the outermost layer of the code are called global scopes, which have the following characteristics:
① It can be accessed anywhere in the code
② If the var keyword is omitted during variable declaration, it is a global variable with global scope
③ The properties and methods of window objects have global scope
④ Open when browser is open, destroy when browser is closed or page is closed

var cat = 'Some fish';
function Person(){
    var name = 'Zhang San';
    per = 'Kaka';// Omit var as global variable
    console.log(cat);//Fish cat is a global variable, which can be accessed inside the function Person
}
console.log(cat);//Fish cat is a global variable, which can be accessed by the outermost code
console.log(per);//The card per is a global variable, which can be accessed by the outermost code

Global scope also has disadvantages, such as: variable naming is easy to repeat, resulting in variable pollution;
Function scope
Variable permission within a function is called function scope, which has the following characteristics:
① Each function has its own scope, and a single call generates a new scope
② It can only be accessed inside a function, but not outside
③ Open when entering the function, and destroy after the function is executed

var cat = 'Some fish';
function Person(){
    var name = 'Zhang San';
    console.log(name);//Zhang san name is the function scope, which can be accessed inside the function Person
}
console.log(name);//Fish name is the function scope, the outermost code does not have permission to access

Block scope (new in ES6)
All the knowledge points wrapped by {} symbols are block scopes. The new knowledge points of ES6 have the following characteristics:
① Can only work inside {}
② Use let or const keywords when declaring variables
③ Variable name cannot be duplicate, otherwise an error will be reported
④ Variable cannot be used before declaration
Use var to show:

if(true){
    var cat = 'Some fish';
    console.log(cat);//Some fish
}
console.log(cat);//Some fish

Use let to show:

if(true){
    let cat = 'Some fish';
    console.log(cat);// Some fish
    // let cat = 'every year'; / / uncaught syntax error: identifier 'cat' has already been declared

}
console.log(cat);// Unable to access cat variable: Uncaught ReferenceError: cat is not defined

Note: block scope is generally used in loop statements such as for to avoid variable leakage


(3) Variable promotion and function promotion
Variable lifting
① var keyword has variable promotion, let and const do not exist;
② Variable promotion means to check whether there is variable declaration in the whole code before executing the program, that is, whether there is a var keyword. If there is, execute the declaration first, and then execute other parts.
Here I sum up four sentences:
① js program execution order, first look at the var declaration, the declaration part is on the first line, and other (assignment) is executed in the normal order
② If there is a var declaration in a local variable, it is a local variable, regardless of the external global variables
③ If there is no var declaration in the local variable, go to the external global variable
④ In local variables, how to use global variables and use window object to call

var a = "Hello";
function person(){
    var a;
    console.log(a);//undifined
    a = "World";
    console.log(a);//World
}
person();
console.log(a);//Hello
// First, look at the declaration part of the whole script file. There is a variable a in the global scope and a variable a in the local scope, and all of them have var declarations, indicating that they are totally two different variables. At this time, the function does not need to care about the external global variables. At this time, the variable a is only declared but not assigned, so the output is undefined;
// Then, in the local scope, a is assigned. At this time, the output is world, and it is still a local variable;
// When outputting the external function, because the local scope has ended, it will be restored to the global variable, so the output is the global variable, whose value is hello.
var a = "Hello";
function person(){
    console.log(a);//Hello
       a = "World";
    console.log(a);//World
}
person();
console.log(a);//World
// First look at the declaration part of the whole script file. There is a variable a in the global scope. If there is no var declaration in the local scope, then a is all variables, so the value of a is all variables hello when outputting;
// Global variable a is reassigned in the local scope, so the output is world
// When the output outside the function is out of the local scope, it is restored to the global variable. Previously, it has been reassigned to world, and the output is world
var a = "Hello";
function person(){
   console.log(a);//undifined
   var a = "World";
   console.log(a);//World
}
person(); 
console.log(a);// Hello
// First, look at the declaration part of the whole script file. The global scope has a variable a, the local scope also has a variable a, and there is a var declaration. It means that they are two completely different variables. At this time, the function does not need to worry about the external global variables to promote the variables. Remember that only the declaration is promoted and the assignment is not promoted, so the output is unknown;
// In the local scope, a is assigned. At this time, the output is World and it is still a local variable
// When the output of the function is external, because the local scope has ended, it is restored to the global variable, so the output is Hello
var a = "Hello";
function person(){
    console.log(window.a);  //Hello, because it is an attribute of the window object, a is the global variable
    var a = "World";     //Local variable a is defined in this line
    console.log(a);  //World
}
person();
console.log(a);//Hello global variable a
// Use global variable in local scope use window. Global variable name

Function enhancement
① Function has two forms: function expression var per = function() {}, function declaration function per() {}, only function declaration has function promotion feature
② Promotion means that it is allowed to call first and then declare

per();//Can be called first
function per(){
    console('I am a function declaration form, which allows promotion');
}


2, Scope chain
(1) What is scope chain
① Each level of scope is actually an execution environment (the scope is different from the execution environment, for easy understanding, let alone this). When executing a program in this environment, a variable object will be created, which contains its own variables and functions;
② When finding invariants in the current execution environment, we will look up the scope of the previous layer. In the specific process, we should first find the variable object of the previous layer, and then find the corresponding variables in it. If we still can't find them, we will continue to look up
③ Until the outermost scope, that is, the global scope, a chain is formed, which is called the scope chain.


(2) Scope characteristics
① The outer layer of the scope chain is the global scope, and the inner layer is the current scope
② The internal environment can access all external environments through the scope chain, but the external environment cannot access any variables and functions of the internal environment
③ Because the search of variables is implemented along the scope chain, it is also called the scope chain as the mechanism of variable search

var cat = 'Some fish';
function Person() {
    var name = 'Zhang San';
    function Student() {
        var age = 18;
        console.log(name);//Zhang San
        console.log(cat);//Some fish
    }
    Student();
    console.log(age);//Uncaught ReferenceError: age is not defined
}
Person();
①Student Function internal belongs to innermost scope, cannot be found name,Up scope Person Function internal search, output found'Zhang San';
②stay Student Internal output cat Cannot find, up scope Person The function is not found. Continue to find the upper level, i.e. global scope. The output is found'Some fish';
③stay Person Function internal output age Can't find when, go up to the scope, i.e. global scope, or can't find the output'age is not defined';

Tags: Front-end Attribute

Posted on Sun, 09 Feb 2020 22:16:47 -0800 by morris520