Created
January 29, 2011 16:24
-
-
Save getify/801962 to your computer and use it in GitHub Desktop.
explaining __proto__ in prototypal inheritance
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
function A() {} | |
var a = new A(); | |
function B() { | |
function F(){} | |
F.prototype = a; | |
return new F(); | |
} | |
var b = new B(); // `b` now inherits from `a` (*not* `A`) | |
console.log(b.constructor == A); // true; but a little weird, because we used `B` to construct `b` | |
console.log(b.__proto__ == a); // true |
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
function A() {} | |
var a = new A(); | |
var b = Object.create(a); // `b` now inherits from `a` (*not* `A`) | |
console.log(b.constructor == A); // true; a little clearer now why, since there is no `B` | |
console.log(b.__proto__ == a); // true |
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
function A() {} | |
var a = new A(); | |
function B() {} | |
B.prototype = a; | |
var b = new B(); // `b` now inherits from `a` (*not* `A`) | |
b.constructor = B; // b.constructor defaults to `A`, so we fix it, to make more sense | |
console.log(b.constructor == B); // true | |
console.log(b.__proto__ == a); // true | |
console.log(Object.getPrototypeOf(b) == a); // true | |
console.log(b.__proto__ == b.constructor.prototype); // true | |
console.log(Object.getPrototypeOf(b) == b.constructor.prototype); // true | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment