Important thing to understand here is, all the names in JavaScript are references to other objects.
When you create an Object with Object literal, the left hand side names are used to refer the objects already referred by the right hand side names.
In this case, when you do
blog: loca,
you are saying blog
to refer the value referred by loca
, which is 5. Later on when you increment loca
, it becomes 6
, it means it refers to some other value, but blog
still refers to the value 5
.
That is why you are getting 5
.
But when you do
namepace.frog()
you are getting the current value referred by loca
. Since it is assigned 6
in getLocal
, you are getting 6
.
Incrementation creates new number object
To make it even more clear, when you do
loca += 1;
or
loca++;
what internally happens is, something like this
oldValue = loca
newValue = oldValue + 1
loca = newValue
Reference from ECMAScript 5.1 Specification, for +=
and for ++
Since numbers are immutable objects (can you change the value of 5
? You cannot, that is why it is called an immutable object), a new number object is created with one added to it and the name loca
is made to refer the new object.
Mutable Objects
If you think about mutable objects,
var namepace = (function () {
var loca = [];
return {
glob: function () {
loca.push(1);
return loca;
},
blog: loca,
frog: function () {
return loca;
}
};
})();
console.log(namepace.glob());
// [ 1 ]
console.log(namepace.blog);
// [ 1 ]
console.log(namepace.frog());
// [ 1 ]
Now, both blog
and loca
refer the same array object. What happens in glob
is called mutating. You are just adding one element to the array object referred with two names blog
and loca
. That is why namepace.blog
also prints [ 1 ]
.