Proto Inheritance

Proto Inheritance

by bhupendra negi

JavaScript

// objecxt prototype
// below prototype object got created when Object fn was defined
var objPro = Object.prototype;
objPro.constructor === Object;

// when a new constructor function is created
// constructor fn creates object (via new) linked to its prototype
function Foo(who) {
  this.me = who;
}
/* when foo function got created its prototype is also got created and this protoype 
object has a special link to Object.prototype using below options :
1) __proto__
2) Object.getPrototypeOf(Foo.prototype)
*/
Foo.prototype.identify = function() {
  return "I am :" + this.me;
}

// use of new keyword to create instances from Foo constructor function
/*
1) a new object is created
2) Links to the prototype of constructor function { Foo.prototype } 
3) the new object is passed into constructor function { Foo}
4) implicitly returns the new object
*/

var a1 = new Foo("a1");
// link from a1 to Foo.prototype can be exposed as
//a1.constructor.prototype <===> Foo.prototype <===> a1.__proto__; 

// shadowing the Foo.prototype
a1.identify = function() {
  return "Shadowed :" + this.identify(); // this will result in infinite loop
}

// in order to access identify from Foo.prototype's below logic can be used
// return "Shadowed :"+ this.__proto__.identify.call(this); 
// but issue is when there are many objects in the linkage we have to use __proro__ many times, to resolve this issue we can use
a1.identify = function() {
  return "Shadowed :" + Foo.prototype.identify.call(this); // this will not result in loop
}

// ******************** Linking Other Constructor functions ****************** //
// now when bar function is declared , its prototype ie Bar.prototype will link to Object.prototype by default. In order to link it to Foo's prototype we need to break linkage between Bar.prototype <===> Object.prototype
function Bar(who) {
  Foo.call(this, who);
}

// reallignment of Bar.prototype to Foo.prototype
Bar.prototype = Object.create(Foo.prototype);
//  Bar.prototype.__proto__...