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.
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];