I’m trying to create a subclass in JavaScript and am encountering an error related to the use of this in the subclass constructor. Here’s the code I’m working with:
class Mammals {
// No constructor defined explicitly
}
class Humans extends Mammals {
constructor(name) {
this.name = name;
}
}
const jimmy = new Humans("Jimmy");
console.log(jimmy.name);
I understand that if a base class has a default no-argument constructor, JavaScript should allow the subclass constructor to run without explicitly calling super(). I thought that since Mammals has a default constructor (as it’s not explicitly defined), the Humans constructor should not need to call super().
However, I am still encountering the error message:
Must call super constructor in derived class before accessing ‘this’
or returning from derived constructor
Can someone explain why
Thank you for your help!