I was reading the following topic How do JavaScript closures work? and found this code:
function foo(x) {
var tmp = 3;
return function (y) {
alert(x + y + tmp);
x.memb = x.memb ? x.memb + 1 : 1;
alert(x.memb);
}
}
var age = new Number(2);
var bar = foo(age); // bar is now a closure referencing age.
bar(10);
The author commented:
As expected, each call to
bar(10)will incrementx.memb. What might
not be expected, is thatxis simply referring to the same object as
the age variable! After a couple of calls to bar,age.membwill be2!
I am confused why it will return 2 always. Can you explain me how it will come 2 always?
It will not “always” be 2.
Author says: “After a couple of calls to bar, age.memb will be 2” – and after 2 calls it will be “2”.
After 4 calls it will be 4.
Just paste this to firebug console: