Sub topic 3
Creating Subclasses with extends
This chapter assumes you can already write a class with a constructor, methods, and fields, and that you know methods live on the class's prototype.
Inheritance with extends and super
class Child extends Parent links Child.prototype to Parent.prototype, so instances inherit the parent's methods. Inside a subclass constructor you must call super(...) before you touch this. Until that call runs, this does not exist, and using it throws a ReferenceError. To override a method, define one with the same name. Inside it, super.method() still reaches the parent's version.
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound.`;
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name);
this.breed = breed;
}
speak() {
return `${super.speak()} Woof!`;
}
}
const d = new Dog('Rex', 'Beagle');
console.log(d.speak()); // 'Rex makes a sound. Woof!'
console.log(d instanceof Dog, d instanceof Animal); // true trueChecking types with instanceof
obj instanceof C walks the prototype chain of obj and looks for C.prototype. That is why d counts as both a Dog and an Animal. The check can fail across realms, for example with objects that come from an iframe.
Subclassing built-ins
You can extend Error, Array, and Map. For errors, pass the message to super and set name so that logs and stack traces show the right type.
class ValidationError extends Error {
constructor(field, message) {
super(message);
this.name = 'ValidationError';
this.field = field;
}
}
try {
throw new ValidationError('email', 'Invalid email address');
} catch (err) {
console.log(err instanceof ValidationError, err.field); // true 'email'
}Abstract bases with new.target
new.target holds the class that new was actually called on. A base class can use it to reject direct instantiation and still allow subclasses.
class Shape {
constructor() {
if (new.target === Shape) throw new TypeError('Shape is abstract');
}
}
class Square extends Shape {
constructor(side) { super(); this.side = side; }
area() { return this.side ** 2; }
}
console.log(new Square(3).area()); // 9Mixins
A class can extend only one parent. A mixin works around this. It is a function that takes a base class and returns a class expression that extends it.
const Serializable = (Base) => class extends Base {
serialize() { return JSON.stringify(this); }
};
class User { constructor(name) { this.name = name; } }
class SerializableUser extends Serializable(User) {}
console.log(new SerializableUser('Ada').serialize()); // '{"name":"Ada"}'Exercise
Why does class B extends A { constructor() { this.x = 1; super(); } } throw when you call new B()?
Show answer
In a derived class, this does not exist until super() runs. Assigning this.x before calling super() throws a ReferenceError.
Exercise
How would you make Serializable and a second mixin Timestamped both apply to User?
Show answer
Nest the calls: class U extends Timestamped(Serializable(User)) {}. Each mixin extends the class returned by the one inside it.