Why The Property Of An Object Would Be Undefined When It's Assigned To 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 variab
Solution 1:
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
.
Post a Comment for "Why The Property Of An Object Would Be Undefined When It's Assigned To The Object?"