In the JavaScript, we can implement the Inheritance using the some alternative ways and we can’t define a class keyword but we create a Constructor function and using new keyword achieves it.
The some Alternative ways As,
1. Pseudo classical Inheritance
2. Prototype Inheritance
Pseudo classical Inheritance is the most popular way. In this way, create a constructor function using the new operator and add the members function with the help for constructor function prototype.
The Prototype based programming is a technique of object oriented programming. In this mechanism we can reuse the exiting objects as prototypes.
The prototype inheritance also known as prototypal, classless or instance based inheritances.
The prototype inheritance also known as prototypal, classless or instance based inheritances.
Example as,
// Create a helper function. if (typeof Object.create !== 'function') { Object.create = function (obj) { function fun() { }; fun.prototype = obj; return new fun(); }; } //This is a parent class. var parent = { sayHi: function () { alert('Hi, I am parent!'); }, sayHiToWalk: function () { alert('Hi, I am parent! and going to walk!'); } }; //This is child class and the parent class is inherited in the child class. var child = Object.create(parent); child.sayHi = function () { alert('Hi, I am a child!'); };
<button type="submit" onclick="child.sayHi()"> click to oops</button>
The output is : Hi, I am a child!
I hope you are enjoying with this post! Please share with you friends. Thank you.