Tommy Tommy - 4 months ago 7
Javascript Question

javascript closure(Why only result3's output is effected by nAdd() )

function f1() {    
var n = 999;    
nAdd = function() {
n += 1
}    
function f2() {      
alert(n);    
}    
return f2;  
}  
var result1 = f1();
var result2 = f1();
var result3 = f1();  

nAdd();
result1(); //999
result2(); //999
result3(); //1000


I had a try that the nAdd() function only effect the 'closure' which is nearest to it. EXample:the result3()'output is 1000.

But I don't know the reason??

Can you give me a answer?

Answer

It has to do with when nAdd is assigned the function. Note that when you create a closure, a new "copy" (for lack of a better word) of the local variables are created. Thus, result1's n is different from result2s n which is different from result3's n. They are seperate, and each closure cannot access another closure's n.

Look at this line:

nAdd = function() {
     n += 1;
}

This assigns nAdd a new closure each time. Each time, this closure will only affect the most recent "copy" of n.

So when you are doing.

var result1 = f1(); // assign nAdd for the first time, referring to result1's n.
var result2 = f1(); // re-assign nAdd, now it affects result2's n.
var result3 = f1(); // re-assign nAdd, now it affect result3's n.

nAdd got assigned a new closure each time. The last time, nAdd got assigned a closure with result3's copy of n.

Thus, when you do nAdd(), you only increment result3's n.

Here's an example that might clear things up.

function f1() {    
    var n = 999;    
    nAdd = function() {
        n += 1
    }    
    function f2() {      
        alert(n);    
    }    
    return f2;  
}  
var result1 = f1();
var nAdd1 = nAdd;
var result2 = f1();
var nAdd2 = nAdd;
var result3 = f1();  
var nAdd3 = nAdd;

nAdd3();
result1();  //999
result2(); //999
result3(); //1000
nAdd1();
result1(); // 1000
nAdd1();
result1(); // 1001
nAdd2();
result2(); // 1000
nAdd();
result3(); // 1001 (the most recent nAdd result3's n).

To further elaborate, consider what would happen if you did this instead:

var result1 = f1();
nAdd();
var result2 = f1();
var result3 = f1(); 

result1(); // 1000
result2(); // 999
result3(); //999

Or this:

var result1 = f1();
var result2 = f1();
nAdd();
var result3 = f1(); 

result1(); // 999
result2(); // 1000
result3(); // 999

It becomes obvious that nAdd updates only the most recent invocation's n.!

Comments