JavaScript中一个对象如何从多个父对象继承?
我想有人会这样做:
Fruit.prototype = new Plant ();
Fruit.prototype = new anotherPlant ();
但是 Fruit 的原型(prototype)属性(原型(prototype)对象)将被设置为什么呢?还会是Fruit原来的Parent构造函数的原来的Parent.prototype吗?
最佳答案
你不能。事实上,支持多重继承的语言并不多。
您所做的就是将 Fruit
的 prototype
设置为 Plant
的实例,然后覆盖 它带有 anotherPlant
的实例。和简单的一样;
Fruit.prototype = new anotherPlant ();
但是,不要忘记 JavaScript 有一个继承链。使用上面的内容,如果 anotherPlant
将 Plant
作为其原型(prototype),那么您将从这两个对象继承。
function Plant() {
}
Plant.prototype.foo = 'foo';
Plant.prototype.baz = 'baz-a';
function AnotherPlant() {
}
AnotherPlant.prototype = new Plant();
AnotherPlant.prototype.bar = 'bar';
AnotherPlant.prototype.baz = 'baz-b';
var a = new AnotherPlant();
console.log(a.foo); // foo
console.log(a.bar); // bar
console.log(a.baz); // baz-b
JavaScript 的继承方式与大多数其他语言不同;它使用原型(prototype)继承,这意味着语言通过遵循所使用的构造函数的 prototype
属性来确定函数(类,如果这样更容易的话)的继承链创建实例。
关于javascript - 原型(prototype)继承和原型(prototype)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20205351/