Javascript 向子类也将使用的超类添加函数
我对JS很陌生,似乎每件事都有很多方法可以做,这会让你感到困惑。不管怎样,这就是我想要做的:Javascript 向子类也将使用的超类添加函数,javascript,Javascript,我对JS很陌生,似乎每件事都有很多方法可以做,这会让你感到困惑。不管怎样,这就是我想要做的: //超类 功能动物(名称、来源、类型){ this.name=名称; this.origin=origin; this.type=type; //做某事的函数 this.makeSound=函数(){ 返回“foo”; } } 函数Mamal(名称、原点、类型、重量、高度){ 动物名称(此名称、来源、类型); 重量=重量; 高度=高度; this.makeSound=函数(){ 返回“我是妈妈”; }
//超类
功能动物(名称、来源、类型){
this.name=名称;
this.origin=origin;
this.type=type;
//做某事的函数
this.makeSound=函数(){
返回“foo”;
}
}
函数Mamal(名称、原点、类型、重量、高度){
动物名称(此名称、来源、类型);
重量=重量;
高度=高度;
this.makeSound=函数(){
返回“我是妈妈”;
}
}
如果我正确理解了您的问题,那么您真正想要实现的是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关键字用于类声明或类表达式中
创建一个类作为另一个类的子类
更新
在此处找到原型继承替代方案:
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
在声明了什么之后?方法属于原型,而不是对象本身。您只需从外部修改原型即可实现所需。
实现了
?这是一个新的关键词吗?@zer00ne很好,谢谢你。我想在typescript中,您可以将该类实现为定义其结构的接口。我已经更新了答案,只包含扩展,以更好地解决这个问题。谢谢你的帮助。我对以我上面所做的函数格式创建构造函数很感兴趣。你所做的另一种方法显然更有效,也许更直观,但出于健壮性以外的原因,我不得不以这样的方式创建类方法。@Hedge请使用函数和原型链找到原型继承方法的更新答案。仅供参考,es6中的类基本上只是构建在原型链上的语法糖。