4
var foo = {n: 1}
var bar = foo
foo.x = foo = {n: 2}

console.log(foo) // {n: 2}
console.log(bar) // ​​​{n: 1, x: {n: 2 }}​​​​​

Can someone explain what happened on the third line?

Yash
  • 929
  • 9
  • 25

1 Answers1

1

The line foo.x = foo = {n: 2} does this:

  1. get the object foo is referencing
  2. assign {n: 2} to foo
  3. assign the object that is now referenced by foo to the property x of the object determined in step 1.

This is basically the same code just with a function call where foo is overwritten inside of the function:

var foo = {n: 1}
var bar = foo
foo.x = test();

console.dir(bar);

function test() {
   foo = 2;
   return 3;
}

foo is changed inside of the of test function, but the object foo determined before that.

t.niese
  • 39,256
  • 9
  • 74
  • 101