Sub topic 15
Abstract Base Classes with new.target
This chapter assumes you already know how extends and super() work, how methods live on the prototype, and how class fields are initialized. You will use new.target to build base classes that cannot be instantiated directly but can still be extended. You will also see where this pattern stops working.
What new.target Is
new.target is a meta-property. It is available inside any non-arrow function, and it refers to the constructor that the new operator was called on. If the function was called without new, its value is undefined.
In a class hierarchy, new.target keeps the same value while super() runs. When you write new Child(), the parent constructor sees new.target === Child, not Parent. That one fact is what makes the abstract-class pattern possible.
class Base {
constructor() {
console.log(`Base constructor, new.target is ${new.target.name}`);
}
}
class Child extends Base {
constructor() {
super();
console.log(`Child constructor, new.target is ${new.target.name}`);
}
}
new Base();
// Base constructor, new.target is Base
new Child();
// Base constructor, new.target is Child
// Child constructor, new.target is ChildThe Abstract Base Class Pattern
JavaScript has no abstract keyword. To get the same effect, the base constructor compares new.target against itself and throws if they match:
class Shape {
constructor() {
if (new.target === Shape) {
throw new TypeError('Shape is abstract and cannot be instantiated directly');
}
}
area() {
throw new Error(`${this.constructor.name} 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).describe()); // 'Square with area 9'
try {
new Shape();
} catch (err) {
console.log(err.message); // 'Shape is abstract and cannot be instantiated directly'
}The base class does two jobs. The constructor check blocks direct instantiation. The area() stub acts as an abstract method: subclasses must override it, and calling the stub throws an error that names the subclass. Shared behavior such as describe() can depend on area() even though the base class never implements it. This is the template method pattern.
Lazy vs. Eager Enforcement of Abstract Methods
The stub approach above is lazy. A subclass that forgets area() constructs fine and fails only when someone calls area(). You can enforce it eagerly instead by checking 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('not implemented');
}
}
class Circle extends Shape {
constructor(r) {
super();
this.r = r;
}
area() {
return Math.PI * this.r ** 2;
}
}
class Blob extends Shape {}
console.log(new Circle(1).area().toFixed(2)); // '3.14'
try {
new Blob();
} catch (err) {
console.log(err.message); // 'Blob must implement area()'
}This works because the prototype chain is already in place when the base constructor runs. this is an object whose prototype is Circle.prototype, so this.area resolves to the subclass method.
| Approach | When the error appears | Catches missing methods in unused code paths | Works with field-defined methods |
|---|---|---|---|
| Lazy stub that throws | When the method is called | No | Yes |
| Eager check in base constructor | When the subclass is instantiated | Yes | No (see below) |
Gotcha: subclass fields do not exist yet
Subclass fields are initialized after super() returns. If a subclass defines its abstract method as an arrow-function field, the base constructor cannot see it yet, and the eager check throws by mistake:
class Shape {
constructor() {
if (this.area === Shape.prototype.area) {
throw new TypeError(`${new.target.name} must implement area()`);
}
}
area() {
throw new Error('not implemented');
}
}
class Triangle extends Shape {
base = 4;
height = 3;
area = () => (this.base * this.height) / 2; // field, assigned after super()
}
try {
new Triangle();
} catch (err) {
console.log(err.message); // 'Triangle must implement area()'
}For the same reason, the base constructor cannot read any subclass field values. If you need eager checks, document that abstract members must be prototype methods, or check new.target.prototype and accept that fields are not covered.
Other Uses of new.target
Making a plain function work with or without new
Before classes existed, constructor functions often protected themselves against a missing new. new.target gives a clean way to do it:
function Temperature(celsius) {
if (!new.target) {
return new Temperature(celsius);
}
this.celsius = celsius;
}
console.log(Temperature(20).celsius); // 20
console.log(new Temperature(25).celsius); // 25Classes do not need this check, because calling a class without new always throws a TypeError.
Per-subclass bookkeeping in the base class
Because new.target identifies the concrete class, a base constructor can keep records for each subclass without any help from the subclasses:
const instanceCounts = new Map();
class Model {
constructor() {
instanceCounts.set(new.target, (instanceCounts.get(new.target) ?? 0) + 1);
}
}
class User extends Model {}
class Order extends Model {}
new User();
new User();
new Order();
for (const [cls, count] of instanceCounts) {
console.log(cls.name, count);
}
// User 2
// Order 1You can also reach the concrete class's static members through new.target, for example new.target.defaults. This lets a base constructor read configuration that each subclass overrides.
Arrow functions inherit new.target
An arrow function has no new.target of its own. It sees the value from the function that encloses it, the same way it inherits this:
class Widget {
constructor() {
const report = () => new.target.name;
console.log(report()); // 'Widget'
}
}
new Widget();Inside an ordinary method called as obj.method(), new.target is undefined. Outside any function, for example at module top level, using new.target is a SyntaxError.
Limits and Failure Modes
It is a runtime check, not a type system
The check runs only when the code executes. Nothing warns you ahead of time that new Shape() appears in your code, and nothing lists which abstract methods a subclass still lacks. TypeScript's abstract keyword gives compile-time errors, but the compiler removes it, so the emitted JavaScript has no runtime guard. Some teams use both.
Reflect.construct can bypass it
Reflect.construct(target, args, newTarget) runs target's constructor with any new.target you choose:
class Shape {
constructor() {
if (new.target === Shape) {
throw new TypeError('Shape is abstract');
}
}
}
const sneaky = Reflect.construct(Shape, [], Object);
console.log(sneaky instanceof Shape); // false
console.log(Object.getPrototypeOf(sneaky) === Object.prototype); // trueThe check passes, but the result is not a real Shape, because its prototype comes from newTarget.prototype. This shows that the pattern guards against mistakes and is not a security boundary. Do not rely on it to protect invariants against hostile code.
Intermediate abstract classes need their own check
Each abstract class checks only against itself. If Polygon extends Shape is also meant to be abstract, Polygon needs its own if (new.target === Polygon) line. The check in Shape does not cover it.
When to Use It
Use a new.target guard when a base class exists only to share behavior and constructing it directly would produce an object with no useful meaning. Common examples are a Shape that has no area or a Repository that has no storage backend. If the base class is usable on its own, skip the guard. If you only need shared methods without a common constructor, a mixin (covered in the next chapter) may fit better.
Exercise
Given class A { constructor() { console.log(new.target.name); } }, class B extends A {}, and class C extends B { constructor() { super(); } }, what does new C() print, and why?
Show answer
It prints C. Calling new C() sets new.target to C. The super() call in C runs B's implicit constructor, and that constructor calls super() into A. new.target stays C at every level, so A logs C.
Exercise
Write an abstract Repository class with a find(id) method that calls an abstract load(id) and caches the results in a private Map. new Repository() must throw. A subclass that does not override load must throw a TypeError naming the subclass when it is constructed.
Show answer
class Repository { #cache = new Map(); constructor() { if (new.target === Repository) throw new TypeError('Repository is abstract'); if (this.load === Repository.prototype.load) throw new TypeError(${new.target.name} must implement load()); } load(id) { throw new Error('not implemented'); } find(id) { if (!this.#cache.has(id)) this.#cache.set(id, this.load(id)); return this.#cache.get(id); } } The eager check works here because load is a prototype method, which already exists on the prototype chain when the base constructor runs.
Exercise
A teammate's subclass defines area = () => this.w * this.h; as a class field, and the base class's eager abstract-method check throws "must implement area()". Explain the cause and give two fixes.
Show answer
Subclass fields are assigned only after super() returns, so when the base constructor runs, this.area still resolves to the base stub. Fix 1: define area() as a prototype method in the subclass. Fix 2: drop the eager constructor check and rely on the lazy stub that throws when area() is called.