Inheritance is an important concept in object-oriented programming. In the classical inheritance, methods from parent class get copied into child class.
In JavaScript, inheritance is supported by using the prototype object. Javascript inheritance also is known as “Prototypal Inheritance” and “Behaviour Delegation”. JavaScript is not a class-based language although class keyword is introduced in ES2015, it is just a syntactical layer. JavaScript still works on the prototype chain
In JavaScript, objects have a special hidden property [[Prototype]]
(as named in the specification), that is either null
or references another object. That object is called “a prototype
First of all, we can create ClassTemp easily. Because there are no explicit classes, we can define a set of behavior (Temp class so…) by just creating a function like below:
var ClassTemp = function() { this.classname = "class Temp"; }
This “class” can be instantiated using the new
keyword:
var a = new ClassTemp(); ClassTemp.prototype.print = function() { console.log(this.classname); }
And to use it using our object:
a.print();
So now we can put all the code in the single program.
var ClassTemp = function() { this.classname = "class Temp"; } ClassTemp.prototype.print = function() { console.log(this.classname); } var a = new ClassTemp(); a.print();
Output Will be: Class A
Why we will use the inheritance in the javascript?
There are multiple reasons to use the inheritance in the javascript which are following.
- It’s simple.
- It’s powerful.
- It leads to smaller, less redundant code.
- It’s dynamic and hence it’s better for dynamic languages.
Only modify your own prototypes. Never modify the prototypes of standard JavaScript objects.