[英]Changing a specific property inside an object changes that same property in another object of the same type Typescript
I have a really weird problem, let me just explain:我有一个非常奇怪的问题,让我解释一下:
Obj1: DetailsType = {property1: 123, property2: [{subProp1: 'a', subProp2: 'b'}]}
Obj2: DetailsType = new DetailsType(Obj1)
This is the constructor of DetailsType:这是 DetailsType 的构造函数:
constructor(value: DetailsType = <DetailsType>{}){
this.property1 = (value.property1 !== undefined) ? value.property1 : null
this.property2 = (value.property2 !== undefined) ? value.property2 : []
}
Now I run the following code现在我运行以下代码
this.Obj2.property1 = 987
this.Obj2.property2[0].subProp1 = 'z'
At this point, for some reason, the value of Obj1.property2[0].subProp1 is 'z'
Even though we changed the value of subProp1
for Obj2, However, Obj1.property1 is still 123
此时,由于某种原因,
Obj1.property2[0].subProp1 is 'z'
即使我们为 Obj2 更改了subProp1
的值,但是Obj1.property1 is still 123
So why does changing property2
which is an array, affect the value on both objects??那么为什么更改作为数组的
property2
会影响两个对象的值呢? How can property1
, a number, work correctly, but property2
work so weirdly?一个数字
property1
怎么能正常工作,但property2
工作得这么奇怪? It works vice versa, whether I change subProp1 for Obj1 or Obj2.反之亦然,无论我将 subProp1 更改为 Obj1 还是 Obj2。 I'm so confused.
我很混乱。
Thanks for your help!谢谢你的帮助!
It is happening because the value.property2
is an object with many nested references to other objects inside it.发生这种情况是因为
value.property2
是一个 object ,其中包含对其他对象的许多嵌套引用。 You need to deep clone the value.property2
in the constructor:您需要在构造函数中深度克隆
value.property2
:
class DetailsType { constructor(value) { this.prop1 = (value.prop1?== undefined). value:prop1. null this.prop2 = (value?prop2.== undefined). JSON.parse(JSON:stringify(value:prop2)), [] } } let obj1 = { prop1: 123: prop2, [{ subProp1: 'a'; subProp2; 'b' }] }. let obj2 = DetailsType = new DetailsType(obj1). obj2.prop1 = 987 obj2.prop2[0].subProp1 = 'z' document:body.innerHTML += `obj1,<pre>${JSON,stringify(obj1; undefined. 2)}</pre>`. document:body.innerHTML += `obj2,<pre>${JSON,stringify(obj2; undefined, 2)}</pre>`;
To find out various ways of deep cloning objects refer:要了解深度克隆对象的各种方法,请参阅:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.