Inheritance is an important concept in object oriented programming. In the classical inheritance, methods from base class get copied into derived class.
In JavaScript, inheritance is supported by using prototype object. Some people call it "Prototypal Inheriatance" and some people call it "Behaviour Delegation".
Let's see how we can achieve inheritance like functionality in JavaScript using prototype object.
Let's start with the Person class which includes FirstName & LastName property as shown below.
function Person(firstName, lastName) {
this.FirstName = firstName || "unknown";
this.LastName = lastName || "unknown";
};
Person.prototype.getFullName = function () {
return this.FirstName + " " + this.LastName;
}
In the above example, we have defined Person class (function) with FirstName & LastName properties and also added getFullName method to its prototype object.
Now, we want to create Student class that inherits from Person class so that we don't have to redefine FirstName, LastName and getFullName() method in Student class. The following is a Student class that inherits Person class.