→ Click here for the code on jsFiddle
function f1(){
var n=999;
nAdd=function(){n+=1;};
function f2(){
alert(n);
}
return f2;
}
var result = f1();
var result2 = f1();
result(); // Output: 999
nAdd();
result2(); // Output: 1000
result2(); // Output: 1000
result(); // Output: 999
I am currently studying JavaScript closures, and the code snippet above has left me feeling perplexed.
The initial call to result()
displays 999, which is understandable.
After invoking nAdd()
, the subsequent call to result2()
yields 1000. This behavior can be attributed to both result2()
and result()
pointing to the same instance of f1()
.
However, I am puzzled as to why the final call to result()
outputs 999 instead of 1000.