gpt4 book ai didi

javascript - 原型(prototype)继承和原型(prototype)属性

转载 作者:行者123 更新时间:2023-11-28 01:46:43 25 4
gpt4 key购买 nike

JavaScript中一个对象如何从多个父对象继承?

我想有人会这样做:

Fruit.prototype = new Plant ();
Fruit.prototype = new anotherPlant ();

但是 Fruit 的原型(prototype)属性(原型(prototype)对象)将被设置为什么呢?还会是Fruit原来的Parent构造函数的原来的Parent.prototype吗?

最佳答案

你不能。事实上,支持多重继承的语言并不多。

您所做的就是将 Fruitprototype 设置为 Plant 的实例,然后覆盖 它带有 anotherPlant 的实例。和简单的一样;

Fruit.prototype = new anotherPlant ();

但是,不要忘记 JavaScript 有一个继承链。使用上面的内容,如果 anotherPlantPlant 作为其原型(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/

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