Body
The concept of closure:
A closure is an expression (usually a function) that has many variables and is bound to these variables. Therefore, these variables are part of the expression.
The most common Closure
Copy codeThe Code is as follows:
Function (){
Var I = 0;
Return function (){
Alert (I ++ );
}
}
Var B = ();
For (var I = 0; I <3; I ++ ){
B ();
}
Before interpreting the code above, we should first accept the creation and execution process of a function.
Step 1: Define the function, set the environment, and create a scope chain. Now a is a global variable, only window
Step 2: execute a, first create the scope (. scope = a), then create the activity object (callObject), and put callObject to the top of the scope chain of a, so a's scope chain contains two objects (a and window)
Step 3: add an arguments attribute to the activity object and save the parameter value when a is called.
Step 4: Assign the parameters and internal variables to activity object.
JavascriptGC principle: if an object is no longer referenced, it will be recycled by GC. If two objects reference each other without interference, the two objects will also be recycled.
Summary:
1. When defining a, the scope chain of a is created)
2. (var B = a () when executing a, create scope a. scope = a and create a callObject object to add the scope of.
3. The arguments attribute is added to object a, and the I and return functions are assigned to the activity object.
4. When executing a, B points to the ruturn function value of a, and the local variable I in a referenced in B does not meet the GC collection standard, activity object a is not recycled. Therefore, B accesses I for the first time and can only access