合并 Javascript 个对象和所有指向它们的引用

Merge Javascript Objects and All References Pointing at Them

在javascript中,变量引用objects are passed a "copy of the reference"。我正在努力解决这个概念,因为它涉及到合并两个对象,以及对这些对象的引用的影响。尝试使用下划线的扩展,采用以下 (coffeescript) 代码:

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"}

正如我们所见,下划线没有'merge'对象。相反,发生的事情是下划线将 b 引用的对象的属性设置在 a 引用的对象上。之后,当我们将 b 持有的引用替换为指向 a 引用的对象时, e 继续持有对 b 最初引用的对象的引用.这是因为 e 没有分配给 b 的引用,而是 b 持有的引用的副本。类似地,d 持有一个引用,而不是对 c 的引用,而是对 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?

如果不更改引用,即访问所有变量并使用新的引用值重新分配它们是不可能的 - 在您的情况下,e = b 就像您所做的那样 b = a

要获得预期的结果,您可能需要 _.extend(a, b); _.extend(b, a); 以便它们具有相同的属性 - 但是它们仍然是两个不同的对象。