var foo = {n: 1};
var bar = foo;
foo.x = foo = {n: 2};
console.log(foo.x) // undefined
I realize that variables store objects as reference. Isn't that foo.x is just another variable? Why it can't point to the the reference as the object?
var foo = {n: 1};
var bar = foo;
foo.x = foo = {n: 2};
console.log(foo.x) // undefined
I realize that variables store objects as reference. Isn't that foo.x is just another variable? Why it can't point to the the reference as the object?
Expanding what you did:
var foo = {n: 1}; // foo = ref#1
var bar = foo; // bar = ref#1
foo.x = foo = {n: 2}; // (ref#1) foo.x = foo (ref#2); foo = ref#2;
console.log(foo.x) // ref#2.x ... which is undefined (from ref#2)
console.log(bar.x) // ref#2 ... which is ref#1
The key is that foo.x
is evaluated first, which results in a reference to ref#1
... to which we then assign ref#2
.