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

150
Vistas
property of undefined (reading 'push') in inheritance method javascript class

I would like to create an array of names containing all names the child has ever had, including the name it is defaulted with.

But when I try to run the code, I get a TypeError: Cannot read properties of undefined (reading 'push').

class Child {
  constructor(name) {
    this.name = name;
    this.names = new Array(name);
  }

  get name() {
    return this._name;
  }

  get names() {
    return this._names;
  }
  set name(newName) {
    this._name = newName
  }

  set names(newName) {
    this.names.push(newName)
  }
}

class Girl extends Child {
  constructor(name = "Sally") {
    super(name);
  }
}

class Boy extends Child {
  constructor(name = "Joe") {
    super(name);
  }
}

const child = new Child();

Can someone explain to me why this is happening? Sorry, I am new to OOP and JavaScript and I can't for the life of me seem to find an explanation for what is happening.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

This has nothing to do with inheritance, the problem is the constructor of the base class.

this.names = new Array(name)

uses the set names function. This pushes onto this._names, but that property has never been created.

The constructor needs to assign the internal _names property so there will be an array for the setter to push onto. So change that line to:

this._names = [name];
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