gpt4 book ai didi

javascript - JavaScript 中的 "inheritance"是什么?

转载 作者:行者123 更新时间:2023-12-03 02:34:05 25 4
gpt4 key购买 nike

谁能用简单的语言向我解释一下 JavaScript 中“继承”的含义?

最佳答案

简单来说,继承是一个事物获得其他事物的属性或行为的概念。说 A 继承自 B,就是说 A 是 B 的类型。鸟 继承自动物,因为鸟 是一种动物 - 它可以做同样的事情,但多一点(或不同)!

在 JavaScript 中,指定这种关系有点复杂,但请注意语法。您必须使用名为 prototype 的特殊对象,它将属性分配给类型,例如 Animal。只有函数才有原型(prototype),这就是为什么您必须首先创建一个函数:

function Animal() {}; // This is the Animal *Type*
Animal.prototype.eat = function () {
alert("All animals can eat!");
};

现在要创建一个继承自 Animal 的 类型,您还可以使用 prototype 对象,但这次属于另一种类型>,例如鸟:

function Bird() {}; // Declaring a Bird *Type*
Bird.prototype = new Animal(); // Birds inherit from Animal
Bird.prototype.fly = function() {
alert("Birds are special, they can fly!");
};

这样做的效果是,您创建的任何鸟类(称为鸟类的实例)都具有动物的属性,但它们还具有附加的 .fly():

var aBird = new Bird(); // Create an instance of the Bird Type
aBird.eat(); // It should alert, so the inheritance worked
aBird.fly(); // Important part of inheritance, Bird is also different to Animal

var anAnimal = new Animal(); // Let's check an instance of Animal now
anAnimal.eat(); // Alerts, no problem here
anAnimal.fly(); // Error will occur, since only Birds have fly() in its prototype

关于javascript - JavaScript 中的 "inheritance"是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5027045/

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