Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

157
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda