javascript 对象属性引用

标签 javascript object properties reference

谁能对这里发生的事情给出最好的解释:

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/

相关文章:

javascript - TinyMCE 插入内容

java - 对象之前的Android编程m

c++ - c++中对象的初始化

java - 如何从属性文件中获取 bean 验证错误消息?

objective-c - Property & Private & Extended Class组合接口(interface)困惑

javascript - 将数据从mysql数据库导入到现有的html5表中

javascript - 如何用 Jest 模拟回调函数

javascript - 如何在图像上放置很棒的字体并模仿悬停属性

java - Java "reference object"是否存在?

javascript - 你能给 Dart 中的函数添加属性吗?