0

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

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

4 Comments

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.
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.
Not exactly. It treats it as undefined. undefined++ === undefined. Setting obj.var = {"foo", "Hello"} will create an object which will be passed by reference.
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".

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.