Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

149
Views
JS subclass with less parameters than parent class

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}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!