Skip to content

Instantly share code, notes, and snippets.

@psiborg
Created January 6, 2012 08:12
Show Gist options
  • Save psiborg/1569630 to your computer and use it in GitHub Desktop.
Save psiborg/1569630 to your computer and use it in GitHub Desktop.
JS Inheritance
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