Created
January 6, 2012 08:12
-
-
Save psiborg/1569630 to your computer and use it in GitHub Desktop.
JS 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
var Person = function (name) { | |
this.name = name; | |
}; | |
Person.prototype = { | |
says: function (saying) { | |
console.log(this.name + ' says "' + saying + '"'); | |
} | |
}; | |
// constructor function | |
var Jedi = function (name, style) { | |
Person.call(this, name); | |
this.style = style; | |
}; | |
Jedi.prototype = new Person(); | |
Jedi.prototype.says = function (saying) { | |
console.log(this.name + ' uses the ' + this.style + ' fighting style, and says "' + saying + '"'); | |
}; | |
Jedi.prototype.lightsaber = function () { | |
console.log("Swooosh!"); | |
}; | |
var fred = new Person("Fred Flintstone"); | |
var obiwan = new Jedi("Obi Wan", "Soresu"); | |
var yoda = new Jedi("Yoda", "Ataru"); | |
var luke = new Jedi("Luke Skywalker", "Shien"); | |
yoda.age = "Unknown"; | |
yoda.says("Do or do not... there is no try."); | |
yoda.lightsaber(); | |
fred.says("Yabba dabba doo!"); | |
if (fred instanceof Jedi) { | |
fred.lightsaber(); // has no method | |
} | |
else { | |
console.warn(fred.name + ' is not a Jedi'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment