Sub topic 15
Abstract Base Classes with new.target
This chapter assumes you know how extends and super() work. It also assumes you can write a constructor and throw errors.
An abstract base class is a class that only exists to be extended. It defines shared structure and behavior. Callers should never create it directly. Many languages have an abstract keyword for this. JavaScript does not, but you can get the same effect with new.target.
What new.target Holds
Inside a constructor, new.target refers to the class that new was called on. This stays true even inside a parent constructor reached through super().
class Base {
constructor() {
console.log(new.target.name);
}
}
class Child extends Base {}
new Base(); // "Base"
new Child(); // "Child"Child has no constructor of its own, so its default constructor calls super(). The Base constructor runs, but new.target is still Child. That lets a base class tell a direct call apart from a subclass call.
Building an Abstract Shape
class Shape {
constructor() {
if (new.target === Shape) {
throw new TypeError('Shape is abstract and cannot be instantiated directly');
}
}
area() {
throw new Error('Subclasses must implement area()');
}
describe() {
return `${this.constructor.name} with area ${this.area()}`;
}
}
class Square extends Shape {
constructor(side) {
super();
this.side = side;
}
area() {
return this.side ** 2;
}
}
console.log(new Square(3).area()); // 9
console.log(new Square(3).describe()); // "Square with area 9"
try {
new Shape();
} catch (err) {
console.log(err.message); // "Shape is abstract and cannot be instantiated directly"
}The design has two guards:
| Guard | What it prevents | When it fires |
|---|---|---|
| `new.target === Shape` check | Creating a `Shape` directly | At construction |
| `area()` that throws | A subclass that forgets to override `area` | When `area()` is first called |
The describe() method is a template method. It lives in the base class and relies on area(), which each subclass supplies.
Common Mistakes
- Checking
this.constructorinstead ofnew.target. This usually works, butthis.constructorreads a normal property that can be overwritten.new.targetis set by the engine. - Using
new.target !== Shapeby mistake. That inverted check blocks every subclass and allows only the base class. That is the opposite of what you want. - Expecting a compile-time error. Both guards run at runtime. A subclass that is missing
area()loads without complaint and only fails whenarea()is called. If you need the failure sooner, check in the constructor:
class Shape {
constructor() {
if (new.target === Shape) {
throw new TypeError('Shape is abstract');
}
if (this.area === Shape.prototype.area) {
throw new TypeError(`${new.target.name} must implement area()`);
}
}
area() {
throw new Error('Subclasses must implement area()');
}
}
class Circle extends Shape {}
try {
new Circle();
} catch (err) {
console.log(err.message); // "Circle must implement area()"
}Exercise
A subclass Triangle extends Shape (the first version above) and defines no constructor. Does new Triangle() throw? What does new Triangle().area() do?
Show answer
new Triangle() does not throw. Triangle's default constructor calls super(), and inside Shape new.target is Triangle, not Shape. Calling area() throws "Subclasses must implement area()" because Triangle inherits the base method without overriding it.
Exercise
Change Shape so that it throws when new.target is any class other than Square or Circle. Which expression would you test?
Show answer
Test whether new.target is in an allow-list, for example: if (![Square, Circle].includes(new.target)) throw new TypeError('Unsupported shape'). Square and Circle must be defined before any instance is created, but they can be declared after Shape, because the check runs at construction time.