gpt4 book ai didi

javascript - Object.create 如何在 Javascript 中不允许多重继承?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:14:22 26 4
gpt4 key购买 nike

MDN在 Javascipt 中给出了继承的解释(带有显示原型(prototype)链的注释):

var a = {a: 1}; 
// a ---> Object.prototype ---> null

var b = Object.create(a);
// b ---> a ---> Object.prototype ---> null
console.log(b.a); // 1 (inherited)

var c = Object.create(b);
// c ---> b ---> a ---> Object.prototype ---> null

var d = Object.create(null);
// d ---> null
console.log(d.hasOwnProperty);
// undefined, because d doesn't inherit from Object.prototype

在我看来,c 是从多个类继承的。这怎么不是多重继承?

最佳答案

多重继承是指父级在层次结构中处于同一级别:

c ---> b ---> Object.prototype ---> null
\---> a ---> Object.prototype ---> null

在这种情况下,它是从类 b 继承的简单继承,该类继承自另一个类 a:

c ---> b ---> a ---> Object.prototype ---> null

附录:虽然效果可能看起来相似(b 的属性也将通过原型(prototype)链中的查找在 c 中“找到”),但请注意不同之处多重继承将允许 ab 具有完全不同的继承链(实际上,继承“树”),这在您的示例中显然不是这种情况。

关于javascript - Object.create 如何在 Javascript 中不允许多重继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29668603/

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