Categories
JavaScript Answers

How to create an abstract base class in JavaScript?

Spread the love

Sometimes, we want to create an abstract base class in JavaScript.

In this article, we’ll look at how to create an abstract base class in JavaScript.

How to create an abstract base class in JavaScript?

To create an abstract base class in JavaScript, we can create a class that other classes can inherit from.

For instance, we write

class Animal {
  constructor() {
    if (this.constructor === Animal) {
      throw new Error("Abstract classes can't be instantiated.");
    }
  }

  say() {
    throw new Error("Method 'say()' must be implemented.");
  }

  eat() {
    console.log("eating");
  }
}

class Dog extends Animal {
  say() {
    console.log("bark");
  }
}

to create the Animal class which throws errors for methods that should be implemented by child classes.

In Animal‘s constructor, we throw an error if the current class is Animal so that we can’t instantiate Animal directly.

Then we create the Dog class, which is a child class of Animal, that implements the methods by overriding the ones in Animal.

Conclusion

To create an abstract base class in JavaScript, we can create a class that other classes can inherit from.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *