Copy codeThe Code is as follows: function f1 (){
Var n = 999;
NAdd = function () {n + = 1 ;}
Function f2 (){
Alert (n );
}
Return f2;
}
Here, the closure is f1, which closes a Variable n and a function f2.
We will ignore nAdd and try to rewrite this function as much as possible.Copy codeThe Code is as follows: function f1 (){
Var n = 999;
Var f2 = function () {alert (n );};
Return f2;
}
Var result = f1 ();
Result ();
Each variable in js is encapsulated as a function. When a variable cannot be found within the function, the function searches for the previous Unit (context) where the function is located, always find the top-level window field.
In this case, the query process starts from the function reference position or the position defined by the function body?
In the above Code, The result field is window, but the actual output result is the n value in f1, so we can draw a conclusion: the start point of Variable Search is the position defined by the function body.
Now let's look at nAdd (the first code ). As we know, variables without the keyword var are entered in the window field by default, so nAdd is actually window. nAdd. This is equivalent to the following code:Copy codeThe Code is as follows: var nAdd;
Function f1 (){
Var n = 999;
NAdd = function () {n + = 1 ;}
Function f2 (){
Alert (n );
}
Return function () {alert (n );};
}
According to our analysis of the result, the execution of nAdd will affect the n value in f1.
So there are:Copy codeThe Code is as follows: function f1 (){
Var n = 999;
NAdd = function () {n + = 1 ;}
Function f2 (){
Alert (n );
}
Return function () {alert (n );};
}
Var result = f1 ();
Result ();
NAdd ();
Result ();
The final output result of this code execution is 1000.
Let's look at this situation again:Copy codeThe Code is as follows: function f1 (){
Var n = 999;
NAdd = function () {n + = 1 ;}
Function f2 (){
Alert (n );
}
Return function () {alert (n );};
}
F1 (); // <-- p1
NAdd ();
F1 (); // <-- p2
Briefly describe the execution process:
Position p1. f1 encapsulates an anonymous closure A. After returning the function A: f2 in the closure A, it then executes the: f2, A: f2 output variable A: n, the result is 999.
At the same time, nAdd is assigned as A function in the closure, and the next row executes nAdd to make the value of A: n + 1.
Position p2, f1 encapsulates anonymous closure B, and all operations are performed on closure B. Then, execute B: f2 to output B: n, so the final result is still 999.
A and B are two independent "packages" that do not affect each other.
Rewrite the call part of the function:
Copy codeThe Code is as follows: function f1 (){
Var n = 999;
NAdd = function () {n + = 1 ;}
Function f2 (){
Alert (n );
}
Return function () {alert (n );};
}
Var result = f1 ();
Result ();
NAdd ();
F1 ()();
Result (); // <-- p3
The position p3 does not mean that the output is 1000.