Skip to content Skip to sidebar Skip to footer

Can Someone Explain The Following Double Assignment Involving Javascript Object

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

Solution 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);

functiontest() {
   foo = 2;
   return3;
}

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

Post a Comment for "Can Someone Explain The Following Double Assignment Involving Javascript Object"