1
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?

Joshua Leung
  • 2,219
  • 7
  • 29
  • 52

1 Answers1

0

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.

Sean Vieira
  • 155,703
  • 32
  • 311
  • 293