var a ={n:1};
var b = a;
a.x=a={n:2};
console.log(1,a);
console.log(2,a.x);
console.log(3,b);
console.log(4,b.x);
解析:
var a = {n:1}; // 开辟一块内存空间a,在栈内存中存入{n:1}的指针0x0012ffc
var b = a; // 开辟一块内存空间b,在栈内存中存入{n:1}的指针0x0012ffc
a.x=a={n:2}; // 1. 创建a的属性;2.更改a的指向为0x0012ffd;3. 给x赋值{n:2}的指针0x0012ffd
这里需要注意顺序问题先创建a的属,在从右向左进行赋值运算。
console.log(1, a); // 打印时候先找a的指针,指向为0x0012ffd {n:2},因此打印为{n:2}。
console.log(2, a.x); // 打印时候先找a的指针,指向为0x0012ffd {n:2},不包含a的属性,因此打印为undefined。
console.log(3,b); // 打印时候先找b的指针,指向为0x0012ffc,因此打印为{n: 1, x: { n: 2 }}
答案: {n: 2}, undefined, {n: 1, x: { n: 2 }}, {n: 2}
编号: 44