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?
asked Sep 6, 2013 at 16:23
Breno Gazzola
2,1801 gold badge16 silver badges36 bronze badges
1 Answer 1
Your bar is not the same references as what i_bar is referencing. Value types are not by reference, so you are copying bar into the return object, but it is not the bar that your function is referring to. Try this:
var obj = function()
{
var self = this;
function i_bar(){return ++self.bar;}
self.bar = 10;
self.i_bar = i_bar;
return self;
}();
answered Sep 6, 2013 at 16:30
Brian Genisio
48.2k17 gold badges128 silver badges168 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
Brian Genisio
Because value types are not passed by reference. Functions and objects are passed by reference. When you construct a new object, you are making a copy of
bar, but it is not the same bar that the function is referring to.Breno Gazzola
You are correct, and initializing
bar as an object fixes it. But what actually confused me was this: I simply declared the variable but didn't assign any value to it. After that I did obj.bar = {"foo" : "Hello"} but i_bar didn't notice the change. I guess that since no value was assigned at creation, javascript decided to treat it as a primitive, not an object, even after it was changed to an object.Brian Genisio
Not exactly. It treats it as
undefined. undefined++ === undefined. Setting obj.var = {"foo", "Hello"} will create an object which will be passed by reference.Breno Gazzola
Well, this is weird. I modified it so
_bar = {"foo" : "Hello"} and i_bar(){return _bar}. If I do obj.bar = {"foo" : "Bye"}, obj.bar.foo will print "Bye", but obj.i_bar().foo will still print "Hello".Explore related questions
See similar questions with these tags.
lang-js