Reputation: 1223
As per my knowledge, objects in JavaScript are copied by reference and not value. But the below code that I wrote is not working as expected. Maybe I don't know the proper behavior. Please provide insight and possible solution to avoid cases like this.
My code:
var a = {
obj:{u:1,v:2,w:3},
setobj:function(objj){
this.obj = objj
}
};
var b = a;
var m = b.obj
console.log(m);
It prints - {u:1,v:2,w:3}
,
then-
var c = a;
c.setobj({x:4,y:5});
console.log(c.obj); //prints {x:4,y:5}
console.log(a.obj); //prints {x:4,y:5}
console.log(b.obj); //prints {x:4,y:5}
but:
console.log(m); //prints {u:1,v:2,w:3}
I was expecting m to contain the reference of b.obj, where b contains reference of a. The latter is working but the former(m's reference) is not working. Please provide an insight over this and tell me what am I missing. Is it very silly assumption of mine or is there something that I don't know?
Upvotes: 1
Views: 86
Reputation: 421
{u:1,v:2,w:3}
is a standalone object and has its reference address.
when you assign obj:{u:1,v:2,w:3}
, obj
reference address is equal to
{u:1,v:2,w:3} address.
when you do c.setobj({x:4,y:5});
a new address will be assigned to obj
.
your code is equal to:
var anotherObject= {u:1,v:2,w:3}
var a = {
obj:anotherObject,
setobj:function(objj){
this.obj = objj
}
};
Upvotes: 2
Reputation: 116190
The object is not copied, but the reference to the object is copied. The references themselves are values.
So, when you write m = b.obj
, m
points directly to the object 1,2,3. m
is not a reference to b.obj
, but a reference to (incidentally) the same object as to which b.obj
is a reference.
So m
and b.obj
are both (now unrelated) references to the same object 1,2,3.
Then, when you overwrite b.obj
, that reference changes to the object 4,5, but m
is still a reference to the original object.
Upvotes: 6