gpt4 book ai didi

javascript - JS : Unexpected inheritance throught . 推()方法

转载 作者:行者123 更新时间:2023-11-28 17:07:41 24 4
gpt4 key购买 nike

我现在正在开发一些在 Canvas 上运行的游戏引擎。我有一些基本的,但现在我想添加 parent 和 child ......一切都运行正常,直到我尝试将对子对象的引用添加到父对象。我的问题有很短的一部分:

// Object that will be parent of obj1
var obj0 = {
childs: [],
someValue: 10,
parent: null
}

// obj1 is defined from obj0 throught Object.assign(), so any change in
// obj1 will NOT reflect to obj0 (I added console.log() to show it)
var obj1 = Object.assign({}, obj0);
console.log("Expected result: false; Result: " + (obj0 == obj1));
obj1.someValue = 5;
console.log("Expected result: false; Result: " + (obj0.someValue == obj1.someValue));

// Now add obj0 as parent to obj1...
obj1.parent = obj0;

// ... and add obj1 as child to obj0 - I need to do this throught .parent
// (I can't directly do some change in obj1)
obj1.parent.childs.push(obj1);

// Everything seems be alright, but... If I look into obj1.childs...
console.log(obj1.childs)
// I see, that .push applied to all objects that are...

如您所见,.push() 方法应用于所有对象(在本例中为两个对象)。

所以我的问题:
1. 为什么?
2. 如何避免这种情况?

提前谢谢您...

最佳答案

obj1 = Object.assign({}, obj0)之后,两者obj0obj1引用相同childs大批。因此,无论您给该数组带来什么突变(例如 push ),都可以通过这两个对象看到。

消除这种不良影响的一种方法是创建一个构造函数(JavaScript 的特长),甚至可能使用 class符号:

class MyClass {
constructor(value) {
this.childs = [];
this.someValue = value;
this.parent = null;
}
}

// Object that will be parent of obj1
var obj0 = new MyClass(10);

var obj1 = new MyClass(5);
console.log("Expected result: false; Result: " + (obj0 == obj1));
console.log("Expected result: false; Result: " + (obj0.someValue == obj1.someValue));

// Now add obj0 as parent to obj1...
obj1.parent = obj0;
obj1.parent.childs.push(obj1);

// Everything is alright.
console.log(obj0.childs);
// Nothing changed here:
console.log(obj1.childs);

关于javascript - JS : Unexpected inheritance throught . 推()方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55364958/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com