通过引用复制到第二个属性的对象即使在删除原始属性后仍然存在? [英] Object copied to second property via reference persists even after original property deleted?
问题描述
我认为对象是作为参考传递的。但是当我删除 b
时,它仍然存在于 c
中。请看这个例子:
I thought objects are passed as reference. But when I delete b
, it still exists in c
. Please see this example:
第一部分对我有意义,因为它通过引用传递:
This first part makes sense to me as its passed by reference:
var a = {b: {val:true}};
a.c = a.b;
a.b.val = 'rawr';
console.log(uneval(a)); // outputs: "({b:{val:"rawr"}, c:{val:"rawr"}})"
现在这部分对我没有意义:
Now this part does not make sense to me:
var a = {b: {val:true}};
a.c = a.b;
a.b.val = 'rawr';
delete a.b;
console.log(uneval(a)); // outputs: "({c:{val:"rawr"}})"
so b
属性已删除,但 c
属性将属性保存为删除前引用的属性。这是javascript中的一个错误吗?
so b
property is deleted, but c
property is holding the properties to what the referenced before delete. is this a bug in javascript?
编辑:
感谢所有回复!所以它不是一个bug,而且这种行为实际上非常好,它允许人们在保留对象的同时更改key/property名称! :)
edit: thanks all to the replies! so its not a bug, and this behavior is actually very good, it allows people to change "key"/"property" names while retaining the object! :)
推荐答案
不,这不是JavaScript中的错误。
No, this is not a bug in JavaScript.
你在做什么 ac = ab
是你要创建另一个指向同一个对象的链接,这意味着 ab
和 ac
引用相同的子对象 {val:rawr}
。
What you are doing with a.c = a.b
is that you are creating another link to the same object, meaning that both a.b
and a.c
are referencing the same sub-object {val: "rawr"}
.
当你执行删除ab
时,你没有删除子对象,你只是删除 ab
来自 a
的属性。这意味着 ac
仍会引用同一个对象。
When you do delete a.b
, you are not removing the sub-object, you are only removing the a.b
property from a
. This means that a.c
will still reference the same object.
如果你要删除 ac
属性,然后子对象将消失。
If you were to delete the a.c
property as well, then the sub-object will vanish.
这篇关于通过引用复制到第二个属性的对象即使在删除原始属性后仍然存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!