【发布时间】:2017-08-10 08:03:49
【问题描述】:
我正在创建一个函数,忘记将所有实例变量作为参数添加,它工作得很好,我认为这是必然的,因为我认为你正在选择要继承的参数,但它似乎工作没有它,所以重申一下,它们是否有必要,如果有,它们传递的目的是什么
class Felidea{
constructor(name,age,sex){
this.name=name;
this.age=age;
this.sex=sex;
this.hasRetractableClaws=true;
this.hasNightVision=true; //instance variables
}
static isSameSex(cat1,cat2){
return cat1.sex===cat2.sex;
}
scratch(){
console.log(this.name + ": scratch scratch scratch");
}
bite(){
console.log(this.name + ": bite bite bite");
}
}
class HouseCat extends Felidea{
constructor(name,age,sex){
super(); //arguements missing, I commonly see this have the same properties as the parent class
//super(name,age,sex,hasRetractableClaws,hasNightVision) this is what I commonly see
}
purr(){
console.log(this.name + ": purr purr purr");
}
}
let spots= new Felidea("spots",4,"female"); // works fine and inherits the
//missing arguements varibles
【问题讨论】:
-
我没有看到任何参数丢失;你的构造函数要求三个,你通过它三个。我错过了什么吗?
-
"JavaScript 函数不检查接收到的参数数量。" w3schools.com/js/js_function_parameters.asp
-
我通常看到 super 获得与构造函数传递给它的参数相同的参数,但没有它们它似乎可以正常工作,所以我试图了解将这些参数传递给 super 函数的目的
-
但是您正在创建一个新的
Felidea,而不是一个新的HouseCat,所以super不参与您的“测试”。
标签: javascript class inheritance super