Skip to content

Instantly share code, notes, and snippets.

@getify
Created January 29, 2011 16:24
Show Gist options
  • Save getify/801962 to your computer and use it in GitHub Desktop.
Save getify/801962 to your computer and use it in GitHub Desktop.
explaining __proto__ in prototypal inheritance
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
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
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