Object.create 如何在 Javascript 中不允许多重继承?
How does Object.create not allow multiple inheritance in Javascript?
MDN 给出了 Javascipt 中继承的解释(注释显示原型链):
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
是从多个 类 继承的。这怎么是不是多重继承?
多重继承是指 parents 在层次结构中处于同一级别:
c ---> b ---> Object.prototype ---> null
\---> a ---> Object.prototype ---> null
在这种情况下,它是从 class b
继承自另一个 class a
:
的简单继承
c ---> b ---> a ---> Object.prototype ---> null
附录: 虽然效果可能看起来相似(b
的属性在 c 中通过原型链中的查找也将是 "found"),但做请注意多重继承将允许 a
和 b
具有完全不同的继承链(实际上,继承 "trees")的区别,这在您的示例中显然不是这种情况。
多重继承是指从两个或更多类并行继承,即有两个或更多直接祖先。他们组成了一棵树。
在你的例子中只有一个 直接祖先:b,a 是b 的直接祖先,但是c 的间接祖先。它们形成一个线性链。
MDN 给出了 Javascipt 中继承的解释(注释显示原型链):
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
是从多个 类 继承的。这怎么是不是多重继承?
多重继承是指 parents 在层次结构中处于同一级别:
c ---> b ---> Object.prototype ---> null
\---> a ---> Object.prototype ---> null
在这种情况下,它是从 class b
继承自另一个 class a
:
c ---> b ---> a ---> Object.prototype ---> null
附录: 虽然效果可能看起来相似(b
的属性在 c 中通过原型链中的查找也将是 "found"),但做请注意多重继承将允许 a
和 b
具有完全不同的继承链(实际上,继承 "trees")的区别,这在您的示例中显然不是这种情况。
多重继承是指从两个或更多类并行继承,即有两个或更多直接祖先。他们组成了一棵树。
在你的例子中只有一个 直接祖先:b,a 是b 的直接祖先,但是c 的间接祖先。它们形成一个线性链。