Inheritance in JavaScript with example

Hello Readers,

Inheritance is an important concept in object-oriented programming (OOP). It forms one of the four pillars of OOP. Usually, in inheritance, methods from base class get copied into derived class.

Now, you might be thinking JavaScript is not an object-oriented programming then why it supports the concept of inheritance?

Yes, in spite of javascript being an object-based scripting language, it supports inheritance by using prototype object. Some people call it “Prototypal Inheritance” and some people call it “Behaviour Delegation“.

Inheritance in JavaScript with example #javascript #inheritance #prototype Click To Tweet

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.

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.

Please note that we have set Student.prototype to the newly created person object. The new keyword creates an object of Person class and also assigns Person.prototype to new object’s prototype object and then finally assigns newly created object to Student.prototype object. Optionally, you can also assign Person.prototype to Student.prototype object.

Now, we can create an object of Student that uses properties and methods of the Person as shown below.

Hope you like this post and got an understanding of inheritance in javascript.

What do you think?

Dear Reader,
If you have any questions or suggestions please feel free to email us or put your thoughts as comments below. We would love to hear from you. If you found this post or article useful then please share along with your friends and help them to learn.

Happy Scripting!