合并 Javascript 对象和所有指向它们的引用 [英] Merge Javascript Objects and All References Pointing at Them
问题描述
在javascript中,引用对象的变量会被传递一个引用副本"一>.我正在努力解决这个概念,因为它涉及合并两个对象,以及对这些对象的引用的影响.尝试使用下划线的扩展,取以下(咖啡脚本)代码:
In javascript, variables referring to objects are passed a "copy of the reference". I am struggling with this concept as it relates to merging two objects, and the effect on the references to those objects. Attempting to use underscore's extend, take the following (coffeescript) code:
a = {
id: 1
type: "cat"
name: "Angry"
}
b = {
id: 1
type: "dog"
owner: "Bill"
}
c = a
d = c
e = b
_.extend(a, b)
b = a
d.home = "Nashville"
console.log(a) //Object {id: 1, type: "dog", name: "Angry", owner: "Bill", home: "Nashville"}
console.log(b) //Object {id: 1, type: "dog", name: "Angry", owner: "Bill", home: "Nashville"}
console.log(c) //Object {id: 1, type: "dog", name: "Angry", owner: "Bill", home: "Nashville"}
console.log(d) //Object {id: 1, type: "dog", name: "Angry", owner: "Bill", home: "Nashville"}
console.log(e) //Object {id: 1, type: "dog", owner: "Bill"}
正如我们所见,下划线并没有合并"对象.相反,下划线将 b
引用的对象的属性设置在 a
引用的对象上.之后,当我们替换b
持有的引用指向a
引用的对象时,e
继续持有该对象的引用最初由 b
引用.这是因为 e
没有分配给 b
的引用,而是分配给 b
的引用副本.类似地,d
持有一个引用,不是对 c
而是对由 a
引用的对象.
As we can see, underscore did not 'merge' the objects. Instead, what has happened is that underscore set the attributes of the object referred to by b
on the object referred to by a
. Later, when we replace the reference held by b
to point at the object referred to by a
, e
continues to hold a reference to the object originally referred to by b
. This is because e
was not assigned a reference to b
, but rather a copy of the reference held by b
. Similiarly, d
holds a reference, not to c
but to the object referred to by a
.
我想找到一种真正合并两个对象的方法,以便对两个对象的所有引用都指向一个目标.这在 Javascript 中是可能的,还是由于 Javascript 的对象传递结构而无法执行此操作?
I would like to find a way to truly merge the two objects, so that all references to both objects point at a single destination. Is this possible in Javascript, or am I precluded from doing this as a result of Javascript's object passing structure?
推荐答案
我想找到一种真正合并两个对象的方法,以便对两个对象的所有引用都指向一个目标.这在 Javascript 中是可能的,还是由于 Javascript 的对象传递结构而无法执行此操作?
I would like to find a way to truly merge the two objects, so that all references to both objects point at a single destination. Is this possible in Javascript, or am I precluded from doing this as a result of Javascript's object passing structure?
如果不更改引用,这是不可能的,即可以访问所有变量并使用新的引用值重新分配它们 - 在您的情况下,e = b
就像您所做的 b= 一个
.
That's impossible without changing the references, i.e. having access to all the variables and re-assigning them with the new reference value - in your case, e = b
just as you did b = a
.
要获得预期的结果,您可能需要执行 _.extend(a, b);_.extend(b, a);
使它们具有相同的属性 - 但是它们是两个不同的对象.
To get the expected result, you might want to do _.extend(a, b); _.extend(b, a);
so that they have the same properties - however they stay two different objects.
这篇关于合并 Javascript 对象和所有指向它们的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!