【发布时间】:2020-12-04 06:35:51
【问题描述】:
我认为对象的继承仅适用于从父到子,但我的代码显示了“兄弟”之间的奇怪继承。
所以我想知道,为什么我的数组 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
【问题讨论】:
标签: javascript arrays inheritance prototype