Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 47

Abstract Base Classes with new.target

This lesson is built with resources from youtube.com, exploringjs.com and 1 more site.

Hello! In our last lesson, we mastered strategies for resolving method name conflicts when composing behaviors with mixins, a crucial skill for building robust systems. We saw how to use super for cooperative chaining, Symbol for conflict prevention, and helper functions for isolation.

Today, we shift from the composition of behavior to the enforcement of architectural structure within an inheritance hierarchy. While mixins are excellent for "has-a" relationships, classical inheritance is still the bedrock for "is-a" relationships. Our goal is to use new.target to create abstract base classes that cannot be directly instantiated. This pattern is essential for designing frameworks and libraries where you want to provide a template for developers to extend, but prevent them from using the incomplete template directly.

The Goal: Abstract Classes

In many object-oriented languages, an abstract class serves as a blueprint. It's a class that's designed to be inherited from but is incomplete on its own and thus cannot be instantiated directly. You might have encountered this concept in Java, C++, or C# during your computer science studies.

JavaScript doesn't have a native abstract keyword. However, TypeScript, a superset of JavaScript, does. To see exactly what we're aiming to simulate, let's watch a brief explanation of how abstract classes work in TypeScript.

No BS TS #16 - Abstract Classes in Typescript

This video from the 'No BS TS' series by Jack Herrington quickly demonstrates the core ideas of an abstract class: preventing instantiation and requiring subclasses to implement specific methods.

Watch the segment from 00:46 to 03:34. Pay attention to how the abstract keyword is used on the StreetFighter class to block new StreetFighter(), and how the abstract method getSpecialAttack must be implemented by the Ryu subclass. This is the exact behavior we want to replicate in plain JavaScript.

As you saw, the two key features are:

  1. Non-instantiable: new AbstractClass() throws an error.
  2. Enforces a contract: Subclasses are often required to implement abstract methods defined in the base class.

Our focus today is on achieving the first point using a special JavaScript feature: new.target.


The Tool: new.target

new.target is a meta-property available within any function. Its value depends on how the function is called.

  • When a constructor is called with new (e.g., new MyClass()), new.target inside that constructor is a reference to the constructor itself (MyClass).
  • When a regular function is called without new, new.target is undefined.

The JavaScript new.target meta property

Let's watch a quick introduction to new.target from Steve Griffith to solidify our understanding of its basic behavior.

Watch the first 1 minute and 35 seconds. The key takeaway is the difference in new.target's value when a function is called with and without the new keyword.

This property becomes particularly powerful in the context of class inheritance.


new.target in an Inheritance Chain

Here is the crucial behavior for our goal: when you have a chain of super() calls in an inheritance hierarchy, new.target retains the value of the constructor that was originally invoked with new.

Let's say Dog extends Animal.

  • When you execute new Animal(), new.target inside the Animal constructor is Animal.
  • When you execute new Dog(), the Dog constructor calls super(), which runs the Animal constructor. Inside that Animal constructor, new.target is not Animal; it is Dog, because Dog was the target of the new operator.

This allows a base class to know whether it was instantiated directly or as part of a subclass's construction.

MDN Web Docs: new.target in Constructors
This image provides a clear, concise code example demonstrating how `new.target` refers to the most-derived class (`B`) even when the code is executing within the base class constructor (`A`) due to a `super()` call.

For a deeper understanding of why this works, it helps to know how ES6 class instantiation is designed. The exploringjs.com chapter on classes provides an excellent explanation.

Allocating and initializing instances

This resource explains the underlying mechanics of instance allocation in ES6 classes. It reveals that new.target acts as an implicit parameter passed down through super() calls.

Read the section '15.6.2 Allocating and initializing instances'. You don't need to memorize the Reflect.construct details, but focus on the description of new.target: 'If a constructor is called via super(), the value of new.target is the new.target of the constructor that makes the call.' This is the formal explanation for the behavior we just observed.


Simulating an Abstract Class

Now we can combine these concepts. Inside our base class constructor, we can check if new.target is the base class itself. If it is, we know someone tried to instantiate it directly, and we can throw an error.

Simulating an abstract class with new.target

This article from delicious-insights.com provides a perfect, direct implementation of our goal.

Read the section titled 'What is it for?'. The code example for the Shape class is the key part. Notice the simple but effective check: if (new.target === Shape). This is the complete pattern.

Let's write our own implementation based on this pattern. We'll create an abstract Shape class and a concrete Circle class.

class Shape {
  constructor(x, y) {
    // This is the core of the abstract class pattern.
    if (new.target === Shape) {
      throw new TypeError("Cannot construct Shape instances directly. Please subclass it.");
    }
    
    // This code will only run if a subclass called super().
    this.x = x;
    this.y = y;
  }
  
  // We can also define "abstract methods" by making them throw errors.
  // This enforces the contract that subclasses must override them.
  getArea() {
    throw new Error("Method 'getArea()' must be implemented.");
  }

  toString() {
    return `Shape at (${this.x}, ${this.y})`;
  }
}

class Circle extends Shape {
  constructor(x, y, radius) {
    // `super()` calls the Shape constructor.
    // Inside that call, `new.target` will be `Circle`.
    super(x, y); 
    this.radius = radius;
  }
  
  // Fulfill the contract by implementing the abstract method.
  getArea() {
    return Math.PI * this.radius * this.radius;
  }

  // We can also override and extend parent methods.
  toString() {
    return `Circle of radius ${this.radius} at (${this.x}, ${this.y})`;
  }
}

// --- Let's test it ---

// 1. Attempt to instantiate the abstract class directly
try {
  const genericShape = new Shape(0, 0); // This should fail
  console.log(genericShape);
} catch (error) {
  console.error("Error creating Shape:", error.message); 
  // Expected: Error creating Shape: Cannot construct Shape instances directly...
}

// 2. Instantiate the concrete subclass
try {
  const myCircle = new Circle(10, 20, 5); // This should succeed
  console.log(myCircle.toString()); // Circle of radius 5 at (10, 20)
  console.log("Area:", myCircle.getArea()); // Area: 78.53...
} catch (error) {
  console.error("Error creating Circle:", error.message);
}

This implementation successfully prevents direct instantiation of Shape while allowing Circle to be created, perfectly simulating an abstract base class.

Test your understanding!

You are designing a system for a game. You need an abstract base class called Character which should not be instantiated directly. It should have a name property.

Then, create a concrete class Player that extends Character.

Ensure your code throws an appropriate error if someone tries to do new Character('some-name'), but allows new Player('Arthur') to work correctly.

Show answer

Here's a possible solution:

class Character {
  constructor(name) {
    if (new.target === Character) {
      throw new Error("The Character class is abstract and cannot be instantiated directly.");
    }
    this.name = name;
  }

  attack() {
    throw new Error("Each character type must implement its own attack method.");
  }
}

class Player extends Character {
  constructor(name) {
    super(name); // `new.target` here is `Player`
    this.level = 1;
  }

  attack() {
    console.log(`${this.name} attacks with a sword!`);
  }
}

// Test cases
try {
  const generic = new Character('NPC');
} catch (e) {
  console.log(`Success: Caught expected error -> ${e.message}`);
}

const p1 = new Player('Arthur');
console.log(`Successfully created Player: ${p1.name}`);
p1.attack();

Conclusion

You've now learned how to enforce a common and powerful architectural pattern in vanilla JavaScript, even without a dedicated abstract keyword. This technique is invaluable when you're building systems where you need to guide other developers (or your future self) to use your classes in the intended way.

Key Takeaways:

  • An abstract class is a template for other classes that cannot be created on its own.
  • The new.target meta-property tells you which constructor was targeted by the new operator.
  • In an inheritance chain, new.target refers to the most-derived class, not the base class where super() is being executed.
  • By checking if (new.target === MyBaseClass) in the constructor, you can throw an error and effectively prevent direct instantiation, thus simulating an abstract class.

Next Up

We've spent this module looking at various ways to structure and relate classes through composition and inheritance. In our final lesson for this module, we'll turn our attention to the instance itself and explore a pattern for making objects more ergonomic to use. We will learn how to implement a fluent interface (method chaining) on a custom class, a popular pattern seen in libraries like jQuery and many data manipulation tools.