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
CopyCodeThe 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