Skip to main content

Command Palette

Search for a command to run...

Creating abstract class in Javascript

Published
1 min read
A

As a Senior Principal Engineer at CVSHealth, I specialize in building and optimizing cvs.com to deliver a superior guest experience. Using the latest web technologies, my team and I work diligently to create a user-friendly and intuitive platform that exceeds expectations.

An abstract class is a ‘class’ that is used just for inheritance. We should not be creating objects directly from abstract classes.

Here is the code:

function Car(name) {
  if(this.constructor === Car) {
    throw 'Cannot instantiate abstract class';
  }
  this.name = name;
}

function i12() {
  Car.call(this, 'i12');
}

The key here is the 'constructor' property.

Now, if I execute the following:

c = new i12(); 
console.log(c.name); // "i12"

But trying to instantiate the function 'Car' directly will result in an exception.

c = new Car(); // Uncaught Cannot instantiate abstract class

More from this blog

Adarsh Konchady's Blog

23 posts