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.
- var rectangle = function(len, wid)
- {
- this.type = "rectangle";
- this.len = len;
- this.wid = wid;
- }
- var square = function(len)
- {
- rectangle.call(this, len, len);
- }
- var rectangleObj = new rectangle(2, 3);
- console.log(rectangleObj.len);
- console.log(rectangleObj.wid);
- console.log(rectangleObj.type);
- var squareObj = new square(2);
- console.log(squareObj.len);
- console.log(squareObj.wid);
- 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 the "call" function of the rectangle from the square constructor.
- 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.
- [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.
- rectangle.prototype.getArea = function()
- {
- console.log("i m in Rectangle");
- return (this.len * this.wid);
- }
Let's overide the base class method.
- square.prototype = Object.create(rectangle.prototype);
- square.prototype.constructor = square;
- square.prototype.getArea = function()
- {
- console.log("i m in the square");
- return (this.len * this.len);
- }
Expalnation
- Assign rectangle prototype to square class prototype.
- Assign square constructor to prototype constructor.
- 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.
- console.log(rectangleObj.getArea());
- console.log(squareObj.getArea());
Output
m in Rectangle
6
I m in the square
4
Please find the complete article example
here. Please let me know your feedback/comments. It will motivate me to write better articles.