【问题标题】:Inheritance not only between parent->child, furthermore between all childs of a prototype?继承不仅在父母->孩子之间,而且在原型的所有孩子之间?
【发布时间】: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

https://jsfiddle.net/tkzw2fn8/

【问题讨论】:

    标签: javascript arrays inheritance prototype


    【解决方案1】:

    好的,这将需要一个很长的答案,但对我来说是裸露的, 当你通过原型链继承一个数组“myArray”时,你会得到一个引用,这就是为什么即使你做了类似的事情它也会到处更新

    console.log(myObj.myArray);
    

    最后你会看到它等于你拥有的其余对象,现在真正令人困惑的部分来了,如果你也尝试修改 for 循环内的声明,

    testObj[i].declaration="test"+i;
    

    你会注意到一个不同的行为,那是因为 JS 做了一些叫做“Shadowing”属性的东西,但这只适用于原始类型,这就是为什么当一个数组被改变时,它会随处改变,也就是“通过引用继承,原始类型像“声明”不是。

    因此,为了让您获得每个对象的唯一数组,您必须重新创建该数组“当且仅当您将该数组放在原型链上,因为如果您不这样做,它将通过引用继承”,以更改参考。

    希望这能消除一些困惑

    【讨论】:

      【解决方案2】:

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

      您使用Object.create 创建一些新对象(AA、AB、AC),并使用 A 作为其原型。

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

      由于 AA、AB 和 AC 没有自己的myArray 属性,因此当您访问它时,遵循原型链,您将获得 @ 987654325@来自A.


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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-02-20
        • 2011-02-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-26
        • 1970-01-01
        相关资源
        最近更新 更多