var foo = {n: 1};
var bar = foo;
foo.x = foo = {n: 2};
console.log(foo.x) // undefined
我意识到变量存储对象作为参考。难道foo.x只是另一个变量吗?为什么它不能指向作为对象的引用?
答案 0 :(得分:0)
扩展您所做的事情:
var foo = {n: 1}; // foo = ref#1
var bar = foo; // bar = ref#1
foo.x = foo = {n: 2}; // (ref#1) foo.x = foo (ref#2); foo = ref#2;
console.log(foo.x) // ref#2.x ... which is undefined (from ref#2)
console.log(bar.x) // ref#2 ... which is ref#1
关键是foo.x
首先评估 ,这会导致对ref#1
的引用...然后我们将ref#2
分配给它。