Javascript Inheritance and prototypes

Inheritance

Inheritance are very important part of the Object-Oriented Programming languages such a Java, C# etc.

Inheritance is inheriting properties and methods of the parent or base class into the child or derived class and there are different types of inheritances such as Single Inheritance, Multi-level inheritance, Multiple inheritance, Hierarchical inheritance, Hybrid inheritance and multipath inheritance. In terms of inheritance there are method overloading and overriding are the two very important concepts.

Javascript Inheritance

Javascript is not Object Oriented language like C# or Java it is prototype-based language, even it doesn’t support classes, it only supports objects. By using object cloning we can achieve inheritance in javascript.

We are going to implement below inheritance in javascript:

Javascript Inheritance using prototype

Javascript Inheritance using prototype

Javascript Prototype

Object is the base object in javascript, all the objects inherits and override all the properties and methods from Object.prototype.

Objects created with new Date() is inherited from Date.prototype.

Let’s create custom ParentClass object using constructor function and further you can create object with new keyword:

Adding properties to object using prototype

You can add properties to the existing Parent objects using prototype, so that it will get available with all the child objects.

and also we can add properties to the any existing objects as bellow:

Adding methods to object using prototype

You can add properties to the existing Parent objects using prototype, so that it will get available with all the child objects.

and also we can add properties to the any existing objects as bellow:

Prototype clone and method overriding

First, will create prototype clone of ParentClass parent object, so that its properties and methods get available on ChildClass, its way to create inheritance between classes:

Below is the ways to override the functions of the child class:

Javascript inheritance example 1 using prototype

Below is the output:

Javascript inheritance example 2 using prototype

below is the output :

Leave a Reply

Your email address will not be published. Required fields are marked *