Common mistakes
Using this before super()
class Animal {
constructor(name) {
this.name = name;
}
}
class Dog extends Animal {
constructor(name, breed) {
this.breed = breed;
super(name);
}
}
const rex = new Dog("Rex", "terrier");
console.log(rex.breed);
What Node.js prints
ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor
Why, and the fix
In a subclass, the object that this refers to is set up by the parent’s constructor, so it does not exist until super() has run. Call super(name) as the first thing in the constructor, then set this.breed. The same error comes when a subclass constructor forgets super() altogether.
Calling this.method() inside its own override
class Animal {
speak() {
return "...";
}
}
class Dog extends Animal {
speak() {
return `${this.speak()} woof`;
}
}
console.log(new Dog().speak());
What Node.js prints
RangeError: Maximum call stack size exceeded
Why, and the fix
this.speak() starts the lookup at the dog, so it finds Dog’s speak again: the method calls itself without end until the call stack is full. To reach the parent’s version, write super.speak(), which starts the lookup at Animal.prototype.
Extending an object instead of a class
const animal = {
speak() {
return "...";
}
};
class Dog extends animal {}
console.log(new Dog().speak());
What Node.js prints
TypeError: Class extends value #<Object> is not a constructor or null
Why, and the fix
extends needs a class or a constructor function on its right, something that can be called with new. animal is an ordinary object, as in lesson I2.1. Turn it into class Animal { speak() { … } } and write class Dog extends Animal, or keep objects and use Object.create(animal).
JavaScript in the browser: your browser’s own engine, in a sandboxed worker. Syntax errors are located with acorn 8.18.0, MIT. Licence and source