对象引用的可变重新分配使其他对象保持不变(没有“传递"分配) [英] 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
以获得与 {y:"b"}
等效的 ref
.
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屋!