简体   繁体   English

嵌套对象的更新,奇怪的行为

[英]Updates in nested objects, odd behavior

I have two objects. 我有两个对象。 At one point in my code I want a copy of the first object to be stored in a second object. 在我的代码中的某一点,我想要将第一个对象的副本存储在第二个对象中。

So long all works fine. 这么长时间一切正常。 No to the strange part. 没有奇怪的部分。 If i make any changes to the first object the same change is applied to the second object (which isn't the intention). 如果我对第一个对象进行任何更改,则对第二个对象应用相同的更改(这不是意图)。 I guess thats because some kind of referens between the two is keept. 我猜那是因为两者之间的某种推理是肯定的。

Exampel illustrating the problem: 示例说明了问题:

//First object
var person = {
    value: 1,
    item: 2
}

//Second object
var objSum = {
    contain: person,
    info: "other stuff"
}

//Apply change to first object
person.value = 55;
//Echoing second object
console.log(objSum);
    alert("done");

The log outputs: contain => item: 2, value: 55. info: "other stuff" 日志输出:contains => item:2,value:55。info:“other stuff”

I want it to be: contain => item: 2, value: 1. info: "other stuff" 我希望它是:contains => item:2,value:1。info:“其他东西”

It's probably something simple, but i cant get my head around it. 它可能很简单,但我无法理解它。 Why is this happening, and how can I prevent it 为什么会发生这种情况,我该如何防止它

You need to clone the person-object when assigning it to objSum.contain, otherwise you are assigning a reference to the original object. 在将对象分配给objSum.contain时,您需要克隆person对象,否则您将分配对原始对象的引用。 Most easy way is with jquery : 最简单的方法是使用jquery

var objSum = {
    contain: jQuery.extend({}, person);
};

or 要么

var objSum = {
    contain: jQuery.extend(true, {}, person);
};

if person itself also contains objects 如果人本身也包含对象

You need to clone the object 'person', not referencing it. 您需要克隆对象'person',而不是引用它。

There are several ways to clone the object and also there is famous question and answer already... 克隆对象有几种方法,而且已经有着名的问答了......

What is the most efficient way to deep clone an object in JavaScript? 在JavaScript中深度克隆对象的最有效方法是什么?

For your case, using JSON method will be fine. 对于您的情况,使用JSON方法将没有问题。

//First object
var person = {
    value: 1,
    item: 2
}

//Second object
var objSum = {
    contain: JSON.parse(JSON.stringify(person)), //clone object
    info: "other stuff"
}

//Apply change to first object
person.value = 55;
//Echoing second object
console.log(objSum);
alert("done");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM