Inheritance in javascript

Inheritance in javascript

Inheritance is the most widely used object oriented concept which finds it’s way in most of the programming problems. But what is inheritance and why is it so important? This post will answer all your questions.

Inheritance concept in object oriented programming

Inheritance is an object oriented programming paradigm which facilitates adaption or passing over of the properties and methods of one class to another class. The properties and methods of the base class can be used in the derived class. This saves us a lot of rework and facilitates reuse of the existing code.

Consider the scenario where you have a class called Vehicle. Now the Vehicle can have many ‘types’. It has a type of ‘fuel’ that is allowed to be used to run it. It has a ‘mode’ like land, water or air. It has a ‘color’. Apart from these ‘properties’ it also can have methods like run(), stop() etc.

Now consider a four wheeler ‘Car’. It can derive all the properties from the base class ‘Vehicle’ and can also add on its own specific properties or methods to it. Thus the derived class ‘Car’ inherits the base class ‘Vehicle’.

After having understood the basics of inheritance, lets dive into the details of what inheritance looks like in javascript.

Inheritance in Javascript

Unlike other classical languages where one class inherits from another class, javascript has Prototypal inheritance which means that here one object inherits from another object. This is so due to the fact that we do not have classes in javascript but have only objects.
We make use of prototype for inheritance in javascript.

var class1 = function()
{
this.name = ‘Roshni’;
};
class1.prototype.hello= function(){
console.log(‘Hello’);
};
var class2 = function()
{
this.surname = ‘Devadiga’;
};//class2 will inherit class1
class2.prototype = Object.create(class1.prototype);var objectClass2 = new class2();
//The getName function of class1 is inherited in class2
objectClass2.hello();

In the above example we first created class1. We added a method ‘hello’ in the prototype of class1. We then created class2. The prootype of class2 inherhited the prototype of class1. With this the properties and methods of class1 became visible in class2. In the last statement we called the hello method from the object of class2.

Comments are closed.