This question already has answers here:
Implement multiple inheritance in Javascript
(3个答案)
5年前关闭。
如何在JavaScript中从多个父对象继承对象?
我想一个人会这样做:
但是,Fruit的prototype属性(原型对象)将设置为什么?它仍然是Fruit的原始Parent构造函数的原始Parent.prototype吗?
但是,请不要忘记JavaScript具有继承链。使用上面的方法,如果
JavaScript与大多数其他语言的继承方式不同。它使用原型继承,这意味着该语言通过遵循用于创建实例的构造函数的
(3个答案)
5年前关闭。
如何在JavaScript中从多个父对象继承对象?
我想一个人会这样做:
Fruit.prototype = new Plant ();
Fruit.prototype = new anotherPlant ();
但是,Fruit的prototype属性(原型对象)将设置为什么?它仍然是Fruit的原始Parent构造函数的原始Parent.prototype吗?
最佳答案
你不能实际上,没有多少语言支持多重继承。
您在此处所做的全部工作就是将prototype
的Fruit
设置为Plant
的实例,然后用anotherPlant
的实例覆盖它。和简单一样。
Fruit.prototype = new anotherPlant ();
但是,请不要忘记JavaScript具有继承链。使用上面的方法,如果
anotherPlant
以Plant
作为其原型,则您将从这两个对象继承。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
属性来确定函数(类,如果可以简化类)的继承链。关于javascript - 原型(prototype)继承和原型(prototype)属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20205351/