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!
Where did you get the idea that if a base class has no constructor, JavaScript should allow the subclass constructor to run without explicitly calling super()?
JavaScript requires calling super() before you can access this
so suppose if you never access this
then yea, you don't need to call super
but otherwise you do.
As for why, because unless the class you're deriving from has a chance to call its constructor, that part of the class doesn't exist.
Let's say you did this
class Mammals {
// No constructor defined explicitly
weight = 3;
}
Now in Humans
constructor, you should be able to access this.weight
but you can't if you haven't called super()
(a) because of the rule above but (b) because you can't access something that hasn't been constructed and Animals
has not been constructed until you call super()