Inheritance In JavaScript

Introduction

As all of us know that JavaScript also follows object-oriented concepts, we should be able to implement inheritance in JavaScript also. This implementation is different from other object-oriented languages like C#, Java etc. As there is no class keyword (which recently got introduced with the latest version), it is different to inherit from one class (or constructor) to other class.

Let's directly jump into code!!!
 
Example
 
I have created a class square which is inheriting from rectangular.
  1. var rectangle = function(len, wid)  
  2. {  
  3.     this.type = "rectangle";  
  4.     this.len = len;  
  5.     this.wid = wid;  
  6. }  
  7. var square = function(len)  
  8. {  
  9.     rectangle.call(this, len, len);  
  10. }  
  11. var rectangleObj = new rectangle(2, 3);  
  12. console.log(rectangleObj.len);  
  13. console.log(rectangleObj.wid);  
  14. console.log(rectangleObj.type);  
  15. var squareObj = new square(2);  
  16. console.log(squareObj.len);  
  17. console.log(squareObj.wid);  
  18. console.log(squareObj.type);  
Let's see the output of the above code.

2
3
rectangle
2
2
rectangle

Explanation

I have created a constructor for rectangle and same for square also. I am calling "call" function of the rectangle from the square constructor.
  1. rectangle.call(this,len,len);  
The above line does the job of implementing the inheritance. As you can see, I have not defined any property in the square class. But, I have defined 3 properties in rectangle class like len, wid, and type.
 
The syntax of the call function is shown below.
  1. [base class].call([child class],[arguments for base class constructor]);  
The properties can be overridden in child class also.
 
Let's see how functions in a base class can be overridden in child class. Let us create a function in a base class first.
  1. rectangle.prototype.getArea = function()   
  2. {  
  3.     console.log("i m in Rectangle");  
  4.     return (this.len * this.wid);  
  5. }  
Let's overide the base class method. 
  1. square.prototype = Object.create(rectangle.prototype);  
  2. square.prototype.constructor = square;  
  3. square.prototype.getArea = function()   
  4. {  
  5.     console.log("i m in square");  
  6.     return (this.len * this.len);  
  7. }  
Expalnation
  1. Assign rectangle prototype to square class prototype.
  2. Assign square constructor to prototype constructor.
  3. Override the function that you want to override of the base class. If the function is not overridden, it will call the base class function.
Let's see the output.
  1. console.log(rectangleObj.getArea());  
  2. console.log(squareObj.getArea());  
output
 
I m in Rectangle
6
I m in square
4
 
Please find the complete article example here. Please let me know your feedback/comments. It will motivate me to write better articles.
Ebook Download
View all
Learn
View all