谁能对这里发生的事情给出最好的解释:
var o = {
name: "jack"
};
var z = {
name: o.name
};
o = {};
alert(z.name); // expected undefined, shows "jack" instead
对象属性只是引用吗?销毁对象 o 似乎并没有销毁引用的对象(在本例中为字符串“jack”)。或者,o.name 引用的“jack”是否实际上已被销毁但 z.name 创建了 o.name 的副本?
最佳
// consider this too
var o = {
foo: function () {
return "hello";
}
};
var z = {
m: o.foo
};
o = {};
alert(z.m()); // hello is displayed
最佳答案
您可能会发现这更有趣。
var o = {
name: "Jack"
};
var z = {
name: o
};
//Above assignment of 'o' to z.name will create a new alias to object 'o'.
//So both 'o' and 'z.name' point to same object.
//When you change value inside 'o' it will still reflect in 'z.name'
//because both point to same object
o.name="Jill";
console.log(z.name.name); // Logs : Jill and not Jack.
// Now, here you are actually assigning a new object to 'o'.
// This means now 'o' refers to a new object. But this will no way affect
// the 'z.name' reference, it still points to same object.
o = { name : "Joe"};
console.log(z.name.name); // Logs : Jill again and not Joe
关于javascript 对象属性引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20722291/