function f1(){
var n = 999;
nAdd = function(){ n = 1; }
function f2(){
alert(n);
}
return f2;
}
The closure here is f1, which closes a variable n and a function f2.
Let’s ignore nAdd first and try to keep the original appearance and rewrite this function.
function f1(){
var n = 999 ;
var f2 = function(){ alert(n); };
return f2;
}
var result = f1();
result();
Each variable in js is encapsulated in a function unit. When a variable is not found inside the function, the function will search in the previous unit (context) where it is located, all the way to the top-level window domain. .
A question arises at this time: Does the search process start from the function reference position or the function body definition position?
In the above code, the domain of result is window, but the actual output result is the n value inside f1, so it can be concluded that the starting point of variable search is the position where the function body is defined.
Now look back at nAdd (the first piece of code). As we know, variables defined without the keyword var enter the window domain by default, so nAdd is actually window.nAdd. This is equivalent to the following code:
var nAdd;
function f1(){
var n = 999;
nAdd = function(){ n = 1; }
function f2(){
alert(n);
}
return function(){ alert(n); };
}
Then according to our analysis of result, the execution of nAdd will affect the value of n in f1.
So there is:
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.
Look at this situation again:
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:
At position p1, f1 encapsulates an anonymous closure A, and returns the function A:f2 in the closure of A. Then A:f2 is executed, A:f2 outputs variable A:n, and the result is 999.
At the same time, nAdd is assigned as a function in the closure of A, and the next line executes nAdd to set the value of A:n to 1.
At position p2, f1 encapsulates the anonymous closure B. The operations performed are all for closure B. Then the output of B:f2 is B:n, so the final result is still 999.
A and B are two independent "packages" and do not affect each other.
Rewrite the calling part of the function:
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 p3 position unexpectedly outputs 1000.