我正在尝试 Douglas Crokford 视频中的这个示例,据我所知,更改新对象不应更改旧对象。
var oldObject = {
firstMethod:function(){
console.log("This is first method");
},
secondMethod:function(){
console.log("This is second method");
}
}
var newObject = Object(oldObject);
newObject.thirdMethod=function(){
console.log("thirdMethod");
}
newObject.firstMethod=function(){
console.log("I am not first method");
}
newObject.firstMethod();
oldObject.firstMethod();
输出:
I am not first method
I am not first method
但我预料到了,
I am not first method
This is first method
请告诉我我哪里错了。
最佳答案
如果您调用the Object constructor as a function ,它执行类型转换(在这种情况下什么也不做,因为参数已经是一个对象)。 (如果您要 call it as a constructor 并向其传递一个对象,就像您在那里所做的那样,那么它只会返回该对象)。
newObject
不是一个新对象,它是相同对象。因此,对 newObject
的任何修改也是对 oldObject
的修改。
可能你想要:
var newObject = {};
newObject.prototype = oldObject;
而不是 Object()
调用。
关于javascript - JavaScript 对象是单向链接还是双向链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19971629/