Created
May 15, 2015 14:50
-
-
Save prashcr/5a5a4dad654ad16adb63 to your computer and use it in GitHub Desktop.
Inheritance in JavaScript
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
var d1, d2, d3, d4 | |
function Base() {this.foo = 'foo'} | |
Base.prototype.bar = 'bar' | |
// Superconstructor | |
function D1() {Base.call(this)} | |
// Set prototype to instance | |
function D2() { } | |
D2.prototype = new Base() | |
// Set prototype to Base.prototype | |
function D3() { } | |
D3.prototype = Base.prototype | |
// Set prototype to new Object(), whose prototype is Base.prototype | |
function D4() { } | |
D4.prototype = Object.create(Base.prototype) | |
d1 = new D1() | |
d2 = new D2() | |
d3 = new D3() | |
d4 = new D4() | |
console.log(d1.foo, d1.bar) | |
//-> foo undefined | |
console.log(d2.foo, d2.bar) | |
//-> foo bar | |
console.log(d3.foo, d3.bar) | |
//-> undefined bar | |
console.log(d4.foo, d4.bar) | |
//-> undefined bar |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment