Search code examples
javascriptclassinheritancesuper

Passing arguments in super function in classes: is it needed?


I was creating a function and forget to add all the instance variables in as arguments and it worked just fine, I thought that was necessarily, because I thought you were choosing what arguments in to inherit with that, but its seems to work with out it, so to reiterate, are they necessary and if so what purpose are they passed in for thanks

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(); // arguments 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 arguments variables

Solution

  • You need to pass the arguments. Your test is not correctly done, as you do not create an instance of the extended class, but the base class.

    If you change the last line, see what happens:

    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(); // arguments 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);

    All these properties are now undefined.