Skip to content

Instantly share code, notes, and snippets.

@nmsobri
Last active August 29, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nmsobri/799910644e22ff0bed0d to your computer and use it in GitHub Desktop.
Save nmsobri/799910644e22ff0bed0d to your computer and use it in GitHub Desktop.
How Prototype Inheritance Work In Javascript
/** This 3 Point Is Really Important
1.Every Object in javascript have __proto__ property
2.Only Function in javascript have prototype property and this is where property of that instance of function will be stored
3.__proto__ always point to its ConstructorFunction.prototype
**/
var a = {};
console.log(a.__proto__ === Object.prototype); //true
console.log(a.prototype); //undefined
console.log('--------');
function b(lvl){ this.level = lvl ||99 };
b.prototype.name = 'slier';
console.log(b.__proto__ === Function.prototype); //true cause every function in javascript is an instance of Function Object
console.log(b.prototype); // {name:slier...}
console.log('--------');
var c = new b();
console.log(c.__proto__ === b.prototype); //true
console.log(c.prototype); //undefined
console.log(c.level); //99
console.log(c.name); //slier
console.log(c.constructor) //function b()
console.log('--------');
/*Inheritance [Not Working]*/
function d() {}
var e = new d();
console.log(e.name); //undefined
console.log(e.level) //undefined
console.log('--------');
/*Inheritance [Working]*/
function f(){}
f.prototype = new b();
g = new f();
console.log(g.name) //slier
console.log(g.level) //99
/*Explaination Why first inheritance not working*/
function d() {}
var e = new d();
console.log(e.name); //undefined
console.log(e.level) //undefined
/**
console.log(e.name), will look into `e` instance itself and look for property of `name`.None found.
Js try to traverse its __proto__ that is point to d.prototype.Since we did not augment d.prototype, d.prototype is simply an empty object.
Js try to traverse __proto__ of that empty object and its point to Object.prototype, and this Object.prototype is simply a null.
Thus that is why e.name return undefined
**/
/*Explaination Why second inheritance working*/
function f(){}
f.prototype = new b();
g = new f();
console.log(g.name) //slier
console.log(g.level) //99
/**
console.log(g.name) will look into `g` instance itself and look for property of `name`.None found.
Js try to traverse its __proto__ that is point to f.prototype.And as you know, we already modified f.prototype to instance of b (new b()).
Js will try to look of property `name `in instance of `b`.None found.Js will traverse instaceofb .__proto__ that is point to b.prototype.
Js then will find property of` name` in b.prototype, and as you know, we augment b.prototype property and Js will found it
**/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment