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

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

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