js连续赋值
连续赋值问题
var a = {n:1}; var b = a; a.x = a = {n:2}; console.log(a.x); console.log(b.x);
结果:undefined {n:2}
原因:
a.x = a = {n:2};
a 被重写, a.x也被重写
此时 a被重新赋值为{n:2} a.x 还是{n:1} 即:
a = {n:2};
a.x = {n:2};
等价于 :a.x = (a = {n:2});
但是只执行了第一步,所以a.x为undefined
b.x 为{n:2}