在类中传递超级函数中的参数:是否需要?

时间:2017-03-18 21:14:39

标签: javascript class inheritance super

我正在创建一个函数并且忘记将所有实例变量添加为参数并且它工作得很好,我认为这是必要的,因为我认为你选择了继承的参数,但它似乎工作如果有的话,重申一下,是否有必要,如果有的话,他们的目的是为了感谢

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

1 个答案:

答案 0 :(得分:0)

您需要传递参数。您的测试未正确完成,因为您不创建扩展类的实例,而是创建基类。

如果您更改最后一行,请查看会发生什么:

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 HouseCat("spots",4,"female"); // <--- !!!!!!!
 console.log(spots);

现在所有这些属性都未定义。