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 thatx
is simply referring to the same object as the age variable! After a couple of calls to bar,age.memb
will be2
!
I am confused why it will return 2 always. Can you explain me how it will come 2 always?