我对JS还是很陌生,似乎所有事情都有这么多种方法使您感到困惑。无论如何,这就是我要尝试的方法:
//SuperClass
function Animal(name, origin, type) {
this.name = name;
this.origin = origin;
this.type = type;
//Some function that does something
this.makeSound = function() {
return "foo";
}
}
function Mamal(name, origin, type, weight, height) {
Animal.call(this, name, origin, type);
this.weight = weight;
this.height = height;
this.makeSound = function() {
return "I am a Mamal";
}
}
所以问题是我如何在之后的Animal类中添加一个函数 已经声明它,以便Mamal类(或任何子类)也继承并可以使用它。
答案 0 :(得分:1)
如果我正确理解了您的问题,那么您实际上想要实现的是Mamal
类继承了Animal
类的方法?正如您在您所提的问题中将它们称为“类”一样,我提供了一个带有类而非函数的示例。
如果是这样,您可以这样声明Mamal:
class Mamal extends Animal {
constructor(weight, height) {
super();
this.weight = weight;
this.height = height;
}
// if you want to execute the Animal implementation of makeSound
makeSound() {
return super.makeSound();
}
// if you want to overwrite the Animal implementation of makeSound
makeSound() {
return "I am a mammal";
}
}
extends关键字用于类声明或类表达式中 创建一个班级作为另一个班级的子级。
Sub classing with extends Super class calls with super
更新
在此处找到原型继承的替代方法:
function Animal(name, origin, type) {
this.name = name;
this.origin = origin;
this.type = type;
}
Animal.prototype.makeSound = function () {
return "foo";
};
function Mammal(weight, height) {
this.weight = weight;
this.height = height;
Animal.call(this); // call super constructor.
}
Mammal.prototype = Object.create(Animal.prototype); //inherit the Animal object through the prototype chain
Mammal.prototype.makeSound = function () {
return "I am a mammal";
}; //Overwrite the makeSound method inherited from Animal
const cheetah = new Animal('cheetah', 'Africa', 'mammal');
cheetah.makeSound();
//foo
const mammal = new Mammal('100kg', '1m');
mammal.makeSound();
//I am a mammal