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

151
Views
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 answers
Answer question

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