Body
The concept of closures:
A closure is an expression (usually a function) that has many variables and an environment that binds them, and therefore these variables are also part of the expression.
The most common closures
Copy Code code as follows:
function A () {
var i=0;
return function () {
alert (i++);
}
}
var b=a ();
for (Var i=0;i<3;i++) {
b ();
}
Before interpreting the above code, accept the creation and execution of a function
The first step: Define the function, set the environment, create the scope chain (scope chain) Now A is a global variable, then a scope chain only window
Step two: Execute a, first create the scope (a.scope=a), then create the active object (CallObject), and place the CallObject at the top of the scope chain of a, so a scope chain contains two objects (A and window)
Step three: Add a arguments property to the active object and save the parameter value when you call a
Step Fourth: Assign the parameters and internal variables to the active object a
JAVASCRIPTGC principle: If an object is no longer referenced, the object is reclaimed by GC. If two objects are not interfering with each other, the two objects will also be reclaimed.
Summarize:
1. When first defining a, the scope chain of A is created (scope chain)
2, (var b=a ()) When executing a, create the scope a.scope=a and create the scope of CallObject object add a
3. The Arguments property is added to object A and the I and return functions are assigned to the active object
4, when a B is executed, it points to the Ruturn function value of a, and the local variable I in a, which is referenced in B, does not conform to the GC's recycling criteria, and the activity object A is not reclaimed, so B access I is the first object to access, and only in B.