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?
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?
The line foo.x = foo = {n: 2}
does this:
foo
is referencing{n: 2}
to foo
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.