javascript - 继承不仅在父母->孩子之间,而且在原型的所有孩子之间?
问题描述
我认为对象的继承只能从父母到孩子,但我的代码显示了“兄弟姐妹”之间的奇怪继承。
所以我想知道,为什么我的数组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
解决方案
您有一个对象 (A),其中一个属性具有一个数组作为值。
您使用Object.create
A 作为原型来创建一些新对象(AA、AB、AC)。
对于 AA、AB、AC 中的每一个,您都可以访问该myArray
属性并使用push
它来操作它。
由于 AA、AB 和 AC 没有自己的 myArray
属性,所以当你访问它时,遵循原型链myArray
并从 A中获取。
简而言之:原型继承不会创建继承值的深层副本。
推荐阅读
- regression - 使用逻辑回归错误进行预测 - data.frame 中出现意外的“=”
- reactjs - 我如何“深度链接”来响应 Web 组件,即使它们是隐藏的?
- javascript - react-select 上未显示选项
- html - 在链接中垂直对齐
- pip - 如何检查 pip 是否已安装在 Mac 上
- masstransit - 来自请求客户端的 Masstransit 不一致异常
- azure - 使用并行处理在 S3 或 Azure 中连接小于 1MB 的文件。解决方案应该是可扩展的
- ios - 如何更改整个应用程序的 tintColor?SwiftUI
- r - 检查系统命令是否在 R 中完成
- performance - 对于索引产品属性,更多的短文本字段与更少的字段和更多的单词