public
Last active

explaining __proto__ in prototypal inheritance

  • Download Gist
gistfile1.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12
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
gistfile2.js
JavaScript
1 2 3 4 5 6 7
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
gistfile3.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.