Saturday, December 8, 2018

Inheritance in JavaScript

Prototype chaining means an objects dunder proto or proto will point to another object instead of pointing to the constructor function prototype. If the other object’s dunder proto or proto property points to another object it will results into chain. This is prototype chaining.

//SuperType constructor function
function SuperType(){
this.name = "Virat"
}

//SuperType prototype
SuperType.prototype.getSuperName = function(){
return this.name
}

//SubType prototype function
function SubType(){
this.age = 26
}

//Inherit the properties from SuperType
SubType.prototype = new SuperType();

//Add new property to SubType prototype
SubType.prototype.getSubAge = function(){
return this.age;
}

//Create a SubType object
var subTypeObj = new SubType();
console.log(subTypeObj.name); //Output: Virat
console.log(subTypeObj.age); //Output: 26
console.log(subTypeObj.getSuperName()); //Output: Virat
console.log(subTypeObj.getSubAge()); //Output: 26

Above code defines two consructor functions, SuperType and SubType. By default, SubType.prototype has a constructorfunction which points to the constructor function itself and proto property which inherits the default object properties.

//Inherit the properties from SuperType
SubType.prototype = new SuperType();
Above line rewrites the default prototype or he dunder proto property of the SubType constructon function and makes SubType.prototype to point to an object of SuperType constructor function.

This means that all the properties and methods that typically exists on an instance of SuperType now also on SubType.prototype This means that now, SubType function has access to all the SuperType properties and methods.

//Add new property to SubType prototype
SubType.prototype.getSubAge = function(){
return this.age;
}
After the default prototype of SubType constructor function has been overwritten, by using the above line of code we add a new method getSubAge() on top of what was inherited from SuperType, to the prototype object of SubType constructor function.

Note: New methods must be added to the SubType after the inheritance because inheritance overwrites the existing prototype of SubType


Problems with prototype chaining
As all the properties of the super type prototype are shared among the child objects, if one child modifies the property of the Super type prototype, other children also gets affected. 

To fix this issue, we use constructor to inherit the instance properties and prototype chaining to to inherit methods and share properties

https://hackernoon.com/inheritance-in-javascript-21d2b82ffa6f

No comments:

Followers

Link