Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

151
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda