【问题标题】:Passing arguments in super function in classes: is it needed?在类的超级函数中传递参数:需要吗?
【发布时间】: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


【解决方案1】:

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

如果你改变最后一行,看看会发生什么:

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);

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-15
    • 1970-01-01
    • 2023-01-12
    • 1970-01-01
    • 2022-08-02
    • 2017-01-02
    • 2019-03-18
    • 1970-01-01
    相关资源
    最近更新 更多