Skip to content

JavaScript abstract class | Basics

  • by

JavaScript is a prototype-oriented, not an object-oriented programing language. So JavaScript doesn’t have an abstract class concept.

If you would like a class that cannot be constructed, but whose subclasses can, then you can use new.target:

By definition from another programing language: An abstract class is a class that is declared abstract —it may or may not include abstract methods. Abstract classes can’t be instantiated, but they can be subclassed.

JavaScript abstract class

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script>    
   class Abstract {
    constructor() {
      console.log("Abstract")
      if (new.target === Abstract) {
        throw new TypeError("Cannot construct Abstract instances directly");
      }
    }
  }

  class Derived extends Abstract {
    constructor() {
      super();
      console.log("Derived")
    // more Derived-specific stuff here, maybe
  }
}

const b = new Derived(); // new.target is Derived, so no error
const a = new Abstract(); // new.target is Abstract, so it throws

</script>  

</body>
</html>

Output:

JavaScript abstract class

If you’re specifically looking for requiring certain methods to be implemented, you can check that in the superclass constructor as well:

class Abstract {
  constructor() {
    if (this.method === undefined) {
      // or maybe test typeof this.method === "function"
      throw new TypeError("Must override method");
    }
  }
}

class Derived1 extends Abstract {}

class Derived2 extends Abstract {
  method() {}
}

const a = new Abstract(); // this.method is undefined; error
const b = new Derived1(); // this.method is undefined; error
const c = new Derived2(); // this.method is Derived2.prototype.method; no error

Source: stackoverflow.com/

Let’s see another example below where we implement a class in JavaScript along with abstraction properties.

<!DOCTYPE html>
<html>
<body>
  <script>
    class Employee
    {
      constructor() {
        if(this.constructor == Employee){
          throw new Error(" Object of Abstract Class cannot be created");
        }
      }
      display(){
        throw new Error("Abstract Method has no implementation");
      }
    }
    class Manager extends Employee
    {
      display(){
      //super.display();
      console.log("I am a Manager");
    }
  }
    //var emp = new Employee;
    var mang=new Manager();
    mang.display();
  </script>
</body>
</html>

Output: I am a Manager

Do comment if you have any doubts or suggestions on this Js class topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

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