Inheritance is one of the fundamental concepts of object-oriented programming. Inheritance enables child classes to inherit the properties and methods of parent class. So basically it allows us to reuse and organize code more effectively.
Unlike other object oriented programming language, JavaScript is one of the object-oriented languages that allows us creating objects directly, as it does not provide class keyword.
Let understand inheritance with the example below:
var baseClass = function() {
this.name = "Base class";
}
baseClass.prototype.print = function() {
console.log(this.name);
}
var baseObject = new baseClass();
baseObject.print();
//It will output as following:
Base class
Now let’s add a function inheritsFrom to create "inheritance" between two classes:
var inheritsFrom = function (subclass, baseclass) {
subclass.prototype = Object.create(baseclass.prototype);
};
In the above code, we are cloning the prototype so that base class can inherit all the members and functions from the base class.
Now we will create another class that will be a child of the first one:
var childClass = function() {
this.name = "Child class";
this.address = "In child class";
}
inheritsFrom(childClass, baseClass);
Now because childClass inherited from baseObject, it can use the print function as following:
var childObject = new childClass();
childObject.print();
//It will output as following:
Child class
Now we will override the print function for childClass:
childClass.prototype.print = function() {
baseClass.prototype.print.call(this);
console.log(this.address);
}
//It will output as following:
Child class
In child class
Note here we have used call function to call the base function on the current object (this).
0 Comment(s)