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:
- get the object
foois referencing - assign
{n: 2}tofoo - assign the object that is now referenced by
footo the propertyxof the object determined in step1.
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"