-
-
Save 7u4/dbd12768301790e8d104 to your computer and use it in GitHub Desktop.
javascript's __proto__ and prototype explained
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* __proto__ and prototype | |
* - the __proto__ property the instance's 'parent' up the prototype chain | |
* - the prototype property refers what new instances of the type will have their __proto__ set to, i.e. what will be the new instance's 'parent' up the prototype chain | |
*/ | |
/* Given */ | |
function Object () {} | |
Object.prototype = { | |
__proto__: null | |
}; | |
/* And */ | |
function Function () {} | |
Function.prototype = { | |
__proto__: Object.prototype | |
}; | |
/* When objects are created */ | |
var o = new Object(); | |
/* their __proto__ property is set to Object.prototype, to make them Objects */ | |
o.__proto__ = Object.prototype; | |
/* When new functions are created */ | |
function F () {} | |
/* their __proto__ property is set to Function.prototype, to make them Functions */ | |
F.__proto__ = Function.prototype; | |
/* New instances of F should also be Objects, so Fs prototype refers Object.prototype as its __proto__ */ | |
F.prototype = { | |
constructor: F, | |
__proto__ : Object.prototype | |
}; | |
/* When new Fs are created */ | |
var f = new F(); | |
/* their __proto__ is set to F.prototype, to make them Fs */ | |
f.__proto__ = F.prototype; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment