scope

The execution context is created in the call stack, and we call this context scope (functions create scopes for themselves)

Create a become execution context when function performs internal objects, an execution context defines a function execution environment, function each execution to deserve execution context is unique, so call a function will lead to create multiple execution context, when the function is performed, it produced the execution context will be destroyed

The scope chain

[[scope]] is a collection of execution context objects stored in [[scope]. This collection is linked in a chain called a scope chain

Let’s start with the code:

function a(){
    function b(){
        var b=222
    }
    var a=111
    b()
    console.log(a);
}
var glob = 100
a()
Copy the code

First, let’s look at the code, which runs line by line.

Let’s review the scope: first, the global scope GO creates a GO object: find the parameter and variable declaration, and use the parameter and variable declaration as the attribute name of the GO object with the value undefined

GO{
Glob:undefined

}
Copy the code

The function declaration of the global bureau takes the function name as the attribute name of GO and assigns the value to the function body

GO{
Glob:undefined
a:function
}
Copy the code

Look at the function body: find the parameter and variable declarations as the attribute names of the AO object, with the value undefined

AO{
a:undefined
b:undefined
}
Copy the code

Unify an argument with a parameter (that is, assign the value of the argument to the parameter)

AO{
a:undefined
b:undefined
}
Copy the code

Find the function declaration in the function body and assign the function name to the AO property name

AO{
a:undefined
b:undefined,function
}
Copy the code

Code execution:

GO{
Glob:undefined,100
a:function   }
AO{
a:undefined,111
b:undefined,function,222
}
Copy the code

Since console.log(a) is in the function body, it first looks for the value of a in the AO. If a=111, it prints 111

Let’s look at the scope chain:

A definition a.[[scope]]——–>0:GO{}

A execute a.[[scope]]——–>0:a:AO{} 1:GO{}

B.[[scope]]——–>0:AO{} 1:GO{}

B b. [[scope]] — — — — — — — — > 0: b: AO {} 1: a: AO {} 2: GO {}

The scope chain
0 bAO
1 aAO
2 GO
GO
this window
golb 100
a function
aAO
this window
a 111
b function
Arguments (functions come with)
bAO
this window
b 222
Arguments (functions come with)