Could someone explain to me this behavior?
var obj = function()
{
var _bar = 10;
function i_bar(){return ++_bar;}
return {
bar : _bar,
i_bar: i_bar
}
}();
obj.bar // prints 10, OK
obj.i_bar() // prints 11, OK
obj.bar = 0 // prints 0, OK
obj.i_bar() // prints 12, NOK
Since the only variable is _bar
, shouldn't the last obj.i_bar()
have printed 1
instead of 12
?
Your
bar
is not the same references as whati_bar
is referencing. Value types are not by reference, so you are copyingbar
into the return object, but it is not thebar
that your function is referring to. Try this: