Abstract class in Javascript

Many object orientated language offer the notion of an abstract class.

An abstract class is, conceptually, a class that cannot be instantiated and is usually implemented as a class that has one or more pure virtual (abstract) functions. (source: wikipedia)

 

In C++ for example:

 

Java has also the concept of an abstract class:

Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods. (source: javacoffeebreak)

 

 

In Javascript we don’t have (yet?) the concept of the abstract class build-in but we can implement it by ourselves. We can force a class to not be directly instantiated using the new.target meta property introduced into the language in the ES2015 spec. MDN states:

In class constructors, new.target refers to the constructor that was directly invoked by new. This is also the case if the constructor is in a parent class and was delegated from a child constructor.

 

Example:

Since we can inspect the target we can do the following:

Strictly speaking this is not 100% an abstract class since it doesn’t force the presence of at least one virtual method, but it is the closest we can go based on the language’s features.

BE CAREFUL, NEW.TARGET CANNOT CAN BE TRANSPILED TO ES5. YOU CAN STILL USE IT ON THE BACKEND THOUGH

Leave a Reply

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