对象引用的变量重新分配使其他对象保持不变(无“传递"分配) [英] Variable re-assignment of object reference leaves other object unaltered (no “transitive” assignment)
问题描述
我有一个要替换的对象.
I have an object that I want to replace.
var obj1 = { x: "a" };
var ref = obj1;
var obj2 = { y: "b" };
obj1 = obj2;
这导致 ref
等效于 { x: "a" }
,但我希望它也被更改为指向 obj2
得到 ref
等价于 { y: "b" }
.
This results in ref
being equivalent to { x: "a" }
, but I want it to get changed as well to point to obj2
to get ref
being equivalent to { y: "b" }
.
推荐答案
不可能.JS 通过引用的副本传递对象,因此在步骤 var ref = obj1
中,您实际上并没有像在像 C 这样的语言中那样分配引用指针.相反,您正在创建一个副本指向一个类似于 {x: 'a'}
的对象的引用.
Not possible. JS passes objects by a copy of the reference, so in the step var ref = obj1
you're not actually assigning a reference pointer like you would in a language like C. Instead you're creating a copy of a reference that points to an object that looks like {x: 'a'}
.
有关您拥有的其他选项,请参阅此答案:https://stackoverflow.com/a/17382443/6415214.
See this answer for other options you have: https://stackoverflow.com/a/17382443/6415214.
这篇关于对象引用的变量重新分配使其他对象保持不变(无“传递"分配)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!