Reference Links:
1190000012646488
53086893?locationnum=12&fps=1
52914876
Let's look at a few concepts:
function Call stack
The bottom of the stack is always the global context and the top of the stack is the currently executing context
Function Execution Context
Create phase: Create variable object, establish scope chain, determine this point
Code Execution phase: variable assignment, function reference, execution of other code
function scope
Variables are defined within the body of the function in which they are declared and in the body of any function in which the function is nested.
Scope chain
Contains the collection of objects in the scope at which the function was created, which is a chained link, called the scope chain of the function
Variable resolution
When JavaScript queries the value of a variable, it starts looking for the first object in the chain, and so on, until the last object.
Basic rules for lexical scopes
The execution of the JavaScript function is scoped to the scope chain, which is created when the function is defined.
That is, the scope chain to function execution is still valid when the function is defined.
Give me a chestnut:
varA=2; function F1 () {varA=1; function g () {returnA; } return g ();} function F2 () {varA=1; function g () {returnA; } return g;} F1 ();//1F2 () ();//1
First, let's analyze the object on the scope chain when the function is defined:
The first object is nested function g, the second object is function F2, and the third object is a global object, which is the order of the query variable a when the G function is executed
Then let's look at the basic rules of lexical scopes: the scope chain at which the function executes when it queries the definition
We use the Chrome browser breakpoint to analyze how it works:
Concept involved: function call stack, function execution context
Now let's look at F2:
The above procedure proves that when the function executes, the scope chain of the query definition is queried, and the order of the scope chain is as follows:
The above two results compare to the above results, you can find that the variable query order on the scope chain is the global context, the external function context, and the current function context.
The concept of closures
function objects can be associated with each other through the scope chain, and variables inside the function body can be stored within the scope of the function.
Closures in JavaScript