scope

Personal notes – for reference only

1. Generation of scope

In JavaScript, a scope is a collection of accessible variables, objects, and functions; Isolated variables: variables of the same name do not conflict in different scopes;

2. Scope and execution context

4, ‾\underline{difference:} Difference: global scope, each function creates its own scope. Global execution context: created after the global scope is defined but before code execution. Function execution context: is created when a function is called, but before the function code is executed. A function scope is static, existing as long as the function is defined and does not change. The execution context is dynamic, created when a function is called and released automatically when the function is called.

3. Find variable rules

(4) in scope, my face is red; (4) in scope, my face is red; (4) in scope, my face is red; (4) in scope, my face is red; Search in the execution context of the current scope, if there is none, then search in the execution context of the function scope up to the execution context of the global scope, if there is no execution context of the global scope, then an error!

var b = 'boy';
console.log(b); / / output boy
function fighting () {
    console.log(a); / / output is undefined
    console.log(c); / / output is undefined
    if(a==='apple'){
        a = 'Alice'
    }else{
        a = 'Ada'
    }
    console.log(a); The Ada / / output
    var a = 'Andy'; // The variable a is assigned to Andy
    middle();
    function middle() {
        console.log(c++); // Since the variable c is undefined, NaN is output
        var c = 100; // The variable c is set to 100
        console.log(++c); // the output is 101
        small();
        function small () {console.log(a)} Andy / / input
    }
    var c = a = 88; // c = a = 88;
    function bottom () {
        console.log(this.b); // this is global, so print boy
        b = 'baby';
        console.log(b); / / output baby
    }
    bottom();
}
fighting();
console.log(b); / / output baby

Copy the code

conclusion

The purpose of scope chains is to ensure that the variables and functions that are accessible in the execution environment are in order. Variables in the scope chain can only be accessed up, and are terminated when they reach the window object. The scope chain does not allow downward access. Function (){})(); function(){})(); Immediate execution of formal implementation. If no global scope is found, XXX is not defined. If no global scope is found, XXX is not defined. This kind of chain – like relationship layer by layer is called scope chain.