- 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.
Join the conversation! Your thoughts help the community grow.