Sub topic 11
Creating Subclasses with extends
This chapter assumes you already know how to write a class with a constructor, instance methods, and public fields. It also assumes you know that methods live on the class's prototype object. The next chapter covers super in detail. Here you will use super() only as much as extends needs it.
What extends Does
The extends keyword creates a class that builds on an existing class. The existing class is the parent, also called the base class or superclass. The new class is the child, also called the subclass or derived class. Instances of the child get every method the parent defines, and the child can add its own methods or replace the parent's.
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound.`;
}
rename(newName) {
this.name = newName;
return this;
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name);
this.breed = breed;
}
fetch() {
return `${this.name} the ${this.breed} fetches the ball.`;
}
}
const rex = new Dog('Rex', 'Beagle');
console.log(rex.speak()); // 'Rex makes a sound.' (inherited)
console.log(rex.fetch()); // 'Rex the Beagle fetches the ball.' (own)
console.log(rex.rename('Max').fetch()); // 'Max the Beagle fetches the ball.'Dog never defines speak or rename, yet rex can call both. The call super(name) runs Animal's constructor, so Animal sets this.name and Dog then adds this.breed.
The Two Prototype Links
class Dog extends Animal sets up two separate prototype links, and both are worth knowing.
Dog.prototypegetsAnimal.prototypeas its prototype. This link makes instance methods inherit.Dogitself getsAnimalas its prototype. This link makes static methods and static fields inherit.
class Animal {
static kingdom = 'Animalia';
static create(name) {
return new this(name);
}
constructor(name) {
this.name = name;
}
}
class Dog extends Animal {}
console.log(Object.getPrototypeOf(Dog.prototype) === Animal.prototype); // true
console.log(Object.getPrototypeOf(Dog) === Animal); // true
console.log(Dog.kingdom); // 'Animalia'
const d = Dog.create('Rex');
console.log(d instanceof Dog); // true
console.log(d.constructor.name); // 'Dog'Dog.create is found on Animal through the second link. Inside it, this is Dog, because create was called as Dog.create(...). So new this(name) builds a Dog, not an Animal. This is the usual way to write factory methods that still work in subclasses.
When you read rex.speak, JavaScript checks rex first, then Dog.prototype, then Animal.prototype, and it stops at the first object that has the property.
Overriding Methods
If the child defines a method with the same name as one on the parent, the child's version is found first on the chain, so it wins. This is called overriding.
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound.`;
}
introduce() {
return `Hi! ${this.speak()}`;
}
}
class Cat extends Animal {
speak() {
return `${this.name} meows.`;
}
}
console.log(new Cat('Tom').introduce()); // 'Hi! Tom meows.'introduce is defined on Animal, but this.speak() inside it still finds Cat's speak. The lookup starts from the instance every time, no matter which class defined the calling method. Parent methods can therefore call "hooks" that subclasses fill in.
The parent's version still exists on Animal.prototype. Calling it from the override is done with super.speak(), which the next chapter covers.
The Default Constructor
If a subclass doesn't declare a constructor, JavaScript supplies one that forwards all arguments to the parent:
class Cat extends Animal {
// implicit:
// constructor(...args) {
// super(...args);
// }
}That's why class Dog extends Animal {} in the static example above could still be built with a name. Write your own constructor only when the child needs different parameters or extra setup.
If you do write a constructor in a derived class, it must call super() before it touches this, and it must call it before it returns:
class Animal {
constructor(name) {
this.name = name;
}
}
class Bird extends Animal {
constructor(name) {
this.name = name; // no super() call
}
}
try {
new Bird('Tweety');
} catch (err) {
console.log(err.constructor.name); // 'ReferenceError'
console.log(err.message);
// V8: "Must call super constructor in derived class before
// accessing 'this' or returning from derived constructor"
}The rule exists because in a derived class the parent constructor creates the object. Until super() returns, this doesn't exist yet.
Fields in a Hierarchy
Public fields declared in the parent and in the child both end up as own properties on the instance. The order they are set in matters:
super()runs the parent constructor. The parent's fields are initialized first, then the rest of the parent constructor body runs.- When
super()returns, the child's fields are initialized. - The rest of the child constructor body runs.
Because of this order, a parent constructor sees the parent's field values, even when the child declares a field with the same name:
class Base {
kind = 'base';
constructor() {
console.log('in Base:', this.kind);
}
}
class Derived extends Base {
kind = 'derived';
constructor() {
super();
console.log('in Derived:', this.kind);
}
}
new Derived();
// in Base: base
// in Derived: derivedGotcha: Overridden Methods Called from the Parent Constructor
Overriding combined with the field order above causes a common bug. When a parent constructor calls a method that the child overrides, the override runs before the child's fields exist:
class Widget {
constructor() {
this.render();
}
render() {}
}
class Label extends Widget {
text = 'Hello';
render() {
console.log(`Rendering: ${this.text}`);
}
}
new Label(); // Rendering: undefinedLabel.prototype.render is found right away, because methods sit on the prototype before any instance is created. this.text, on the other hand, is not assigned until super() returns. Here are some ways to fix it:
- Don't call overridable methods from a constructor. Have callers call
render()after construction, or use a static factory that constructs the object and then callsrender(). - Set the needed value in the parent through a constructor argument, so it exists before the hook runs.
What You Can Extend
The part after extends is any expression, not just a class name. It is evaluated once, when the class is defined, and the result must be a constructor or null.
function LegacyPoint(x, y) {
this.x = x;
this.y = y;
}
LegacyPoint.prototype.sum = function () {
return this.x + this.y;
};
class Point3D extends LegacyPoint {
constructor(x, y, z) {
super(x, y);
this.z = z;
}
sum() {
return LegacyPoint.prototype.sum.call(this) + this.z;
}
}
console.log(new Point3D(1, 2, 3).sum()); // 6
try {
class Broken extends {} {}
} catch (err) {
console.log(err.message); // V8: 'Class extends value #<Object> is not a constructor or null'
}Some details on what is allowed:
- Old-style constructor functions work as parents, as the
LegacyPointexample shows. This makes it possible to move older code to classes one piece at a time. - Arrow functions and methods are not constructors, so
extendsrejects them with aTypeError. - Expressions such as
extends pickBase()are allowed. The mixins chapter builds on this. extends nullmakes a class whoseprototypehas noObject.prototypeabove it. Its default constructor fails, because there is no parent constructor for it to call. You would need a constructor that returns an object explicitly. You will rarely need this.
JavaScript supports only single inheritance. Each class has exactly one extends clause.
Common Errors
| Symptom | Cause | Fix |
|---|---|---|
| `ReferenceError` mentioning "super constructor" | Derived constructor used `this` or returned before calling `super()` | Call `super(...)` first, or remove the constructor if all it does is forward arguments |
| Child field is `undefined` inside a method that the parent constructor calls | Child fields are initialized only after `super()` returns | Don't call overridable methods from the constructor |
| `TypeError: Class extends value ... is not a constructor or null` | The `extends` expression evaluated to a plain object, `undefined`, or an arrow function | Check imports and spelling. A circular import often makes the parent `undefined` at definition time |
| Static factory returns parent instances | Factory uses `new Animal(...)` instead of `new this(...)` | Use `new this(...)` so subclasses get their own type |
| Parent's argument is missing | Child constructor called `super()` without forwarding parameters | Pass the parent's arguments: `super(name)` |
Exercises
Exercise
Given class A { static hello() { return 'hi from ' + this.name; } } and class B extends A {}, what does B.hello() return, and which prototype link makes the call work?
Show answer
It returns 'hi from B'. extends sets Object.getPrototypeOf(B) === A, so the static method hello is found on A. Because the call is B.hello(), this inside it is B, and B.name is 'B'.
Exercise
A subclass declares class Timer extends Base { constructor(ms) { this.ms = ms; super(); } }. What happens on new Timer(100), and how do you fix it?
Show answer
It throws a ReferenceError, because this is accessed before super() has created the object. Move super(); to be the first statement, then assign this.ms = ms.
Exercise
In this code, why does new Fancy() log undefined, and how could you rewrite it so it logs '★'? class Plain { constructor() { this.draw(); } draw() {} } and class Fancy extends Plain { symbol = '★'; draw() { console.log(this.symbol); } }
Show answer
Plain's constructor calls this.draw() during super(), before Fancy's field symbol has been initialized. One fix is to remove the draw() call from the constructor and call it after construction: const f = new Fancy(); f.draw();. Another fix is to declare symbol as a getter or prototype method (for example get symbol() { return '★'; }), since it lives on the prototype and exists before any constructor runs.
Exercise
You have function Legacy(v) { this.v = v; } and const arrowBase = (v) => { this.v = v; };. Which one can follow extends, and why?
Show answer
Only Legacy. A normal function declaration is a constructor, so class X extends Legacy {} is valid. Arrow functions have no [[Construct]] behavior and no prototype, so extends arrowBase throws a TypeError when the class is defined.