Home Videos Exercises MCQ Q&A Quiz E-Store Services Blog Sign in Appointment Payment

JavaScript Inheritance

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.


Important Notes:

  • Multiple Inheritance: JavaScript does not natively support multiple inheritance. However, you can achieve similar behavior using mixins.
  • Overriding Methods: Child classes or objects can override methods of their parent by defining them with the same name.
  • Inheritance and this: The this context refers to the instance object in both parent and child.

Key concepts

  • Object.create(proto): Creates a new object with the specified prototype.
  • Prototype Chain: When a property or method is accessed on an object, JavaScript checks its prototype chain for the property.