首页 > 解决方案 > 继承不仅在父母->孩子之间,而且在原型的所有孩子之间?

问题描述

我认为对象的继承只能从父母到孩子,但我的代码显示了“兄弟姐妹”之间的奇怪继承。
所以我想知道,为什么我的数组testObj的所有对象(它们是myObj的孩子)都具有相同的数据。
我的代码仅用于没有特定目的的学习。

// my prototype-obj
const myObj = {
    myArray: [],
    declaration: ""
}

// my array of objects
let testObj = [];

// fill my object
for (i=0; i < 4; i++) {
    testObj[i] = Object.create(myObj);
    testObj[i].myArray.push("content of array " + i);        
}

// print my data
testObj.forEach((eleA,idxA) => {
    console.log("\nobj number "+idxA);        
    eleA.myArray.forEach((eleB,idxB) => {
        console.log(eleB);
    });
});
console output:

obj number 0
content of array 0
content of array 1
content of array 2

obj number 1
content of array 0
content of array 1
content of array 2

obj number 2
content of array 0
content of array 1
content of array 2

https://jsfiddle.net/tkzw2fn8/

标签: javascriptarraysinheritanceprototype

解决方案


您有一个对象 (A),其中一个属性具有一个数组作为值。

您使用Object.createA 作为原型来创建一些新对象(AA、AB、AC)。

对于 AA、AB、AC 中的每一个,您都可以访问该myArray属性并使用push它来操作它。

由于 AA、AB 和 AC 没有自己的 myArray属性,所以当你访问它时,遵循原型链myArray并从 A中获取。


简而言之:原型继承不会创建继承值的深层副本


推荐阅读