Javascript obje.key undefined when assigned to the object itself

I watched a fragment from here

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

When I write foo.x it says undefined. Why is this so? I expected it to be {n: 2}

+4
source share
2 answers

Values ​​are assigned from left to right, so this happens:

foo.x = {n: 2};

which leads to the fact that foo is {n: 1, x: {n: 2}}

then foo is assigned a new value

foo = {n: 2};

which overrides it on {n: 2}.

0
source

foo.x , x foo. 12.14.4 : (ES6, ), , ( ) ( ).

, :

var foo = {n: 1};
var bar = foo;
foo.x = foo = {n: 2};
console.log(foo, bar)
Hide result

var foo = {n: 1};
var bar = foo;
bar.x = foo = {n: 2};
console.log(foo, bar)
Hide result

var foo = {n: 1};
var bar = foo;
foo.x = (foo = {n: 2});
console.log(foo, bar)
Hide result
0

Source: https://habr.com/ru/post/1695929/


All Articles