Abstract Class In JavaScript


Abstraction is a very important concept in OOPS programming. Since we argue that JavaScript also follows OOP concepts, then it should be possible to create the abstract classes in JavaScript also.
Let's try to create an abstract class in JavaScript.
Before going into the topic, I believe, you are aware of inheritance in JavaScript. You can brush up your inheritance concepts here
  1. var AbstractClass = function() {  
  2.     if (this.constructor === AbstractClass) {  
  3.         throw new Error("Can't instantiate abstract class!");  
  4.     }  
  5. };  
  6. AbstractClass.prototype.do = function() {  
  7.     throw new Error("Abstract method!");  
  8. }  
  9. AbstractClass.prototype.type = function() {  
  10.     console.log('this is a class');  
  11. }  
Here, I have created a class named AbstractClass. I have an If block here which checks if the AbstractClass constructor is called, then it will throw an error. It will prevent us from creating its object for the below line.
  1. var abstractClass = new AbstractClass();   
In the same prototype, I have declared 2 more functions. One abstract function is "do" and the other one is a normal function named "type".
Let's try to create a class which will inherit from the AbstractClass. 
  1. var ChildClass = function() {  
  2.     AbstractClass.apply(this, arguments);  
  3. };  
  4. ChildClass.prototype = Object.create(AbstractClass.prototype);  
  5. ChildClass.prototype.constructor = ChildClass;  
  6. ChildClass.prototype.do = function() {  
  7.     console.log('coding now!!!');  
  8. }  
I am creating a class named ChildClass here. It inherits from AbstractClass. As the constructor doesn't take any argument here so passing the arguments will be undefined but that won't be a problem in implementation.
I am implementing the "do" function here. In the abstract class, the "do" function was throwing an error while in this implementation, it will log a message.
Let's create objects and see the implementations. 
  1. var developer = new ChildClass();  
  2. developer.do();  
  3. developer.type();  
Please try the example here.
Please let me know your feedback and comments.