Created
May 30, 2015 19:58
-
-
Save JeffML/3dac61f7abf62b989ef7 to your computer and use it in GitHub Desktop.
Javascript inheritance example, using Object.create(), ctors, and super method calls
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
/* refs: | |
* http://oli.me.uk/2013/06/01/prototypical-inheritance-done-right/ | |
* http://davidshariff.com/blog/javascript-inheritance-patterns/ | |
*/ | |
"use strict"; | |
function Human(name, gender) { | |
this.name = name; | |
this.gender = gender; | |
} | |
Human.prototype = { | |
name : '', | |
gender : '', | |
planetOfBirth : 'Earth', | |
sayGender : function() { | |
console.log(this.name + ' says my gender is ' + this.gender); | |
}, | |
sayPlanet : function() { | |
console.log(this.name + ' was born on ' + this.planetOfBirth); | |
} | |
}; | |
function Martian(name, gender) { | |
Human.call(this, name, gender) | |
}; | |
Martian.prototype = Object.create(Human.prototype, { | |
constructor : { | |
value : Martian | |
}, | |
planetOfBirth : { | |
value : "Mars" | |
}, | |
sayPlanet: { | |
value: function() { | |
Human.prototype.sayPlanet.call(this); | |
console.log((this.gender === "male"? "He" : "She") + " is a Martian"); | |
} | |
} | |
}); | |
var marvin = new Martian("Marvin", "male"); | |
var jane = new Human("Jane", "female"); | |
jane.sayGender(); | |
jane.sayPlanet(); | |
console.log() | |
var marsha = new Martian("Marsha", "female"); | |
marsha.sayGender(); | |
marsha.sayPlanet(); | |
console.log() | |
marvin.sayGender(); | |
marvin.sayPlanet(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment