I created a class Animal and a subclass Shark. Animal's constructor has 5 parameters. I want Shark constructor to have only 3 parameters. But it doesn't seem to work. Why, using super(), can't I extract from parent class only those constructor parameters which I need? So that when I create new instances of Shark, I could pass only 3 arguments, not 5.
class Animal {
constructor(name, age, legs, species, habitat) {
this.name = name;
this.age = age;
this.legs = legs;
this.species = species;
this.habitat = habitat;
}
introduce() {
return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
}
}
class Shark extends Animal {
constructor(name, age, habitat) {
super(name, age, habitat);
this.legs = 0;
this.species = 'shark';
}
}
Why is the property 'habitat' undefined below?
const john = new Shark('John', 15, 'ocean');
-> Shark {name: 'John', age: 15, legs: 0, species: 'shark', habitat: undefined}
The constructor doesn't really care what variable names you pass it, just their positions. So this:
super(name, age, habitat);
is only supplying values for the first three constructor arguments here:
constructor(name, age, legs, species, habitat)
So habitat is undefined because nothing ever sets it.
Instead of reducing the constructor arguments and setting the properties manually, rely on the base class to set its own properties and pass them to its constructor:
class Animal {
constructor(name, age, legs, species, habitat) {
this.name = name;
this.age = age;
this.legs = legs;
this.species = species;
this.habitat = habitat;
}
introduce() {
return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
}
}
class Shark extends Animal {
constructor(name, age, habitat) {
super(name, age, 0, 'shark', habitat);
}
}
const john = new Shark('John', 15, 'ocean');
console.log(john);