Skip to content

Instantly share code, notes, and snippets.

@ditman
Created September 23, 2012 15:48
Show Gist options
  • Save ditman/3772090 to your computer and use it in GitHub Desktop.
Save ditman/3772090 to your computer and use it in GitHub Desktop.
Basic JS inheritance
// Constructor function. Code run by the "new" operator
var Rabbit = function(name) {
// All Rabbit instances have their own property "name"
this.name = name;
}
// All Rabbit instances can speak, of course!
Rabbit.prototype.speak = function(what) {
return this.name + " says: " + what;
}
// Constructor function for Killer Rabbits
var KillerRabbit = function(name, eyes) {
Rabbit.call(this, name); // Call parent constructor
this.eyes = eyes;
}
// Make this have a "Rabbit" prototype
KillerRabbit.prototype = new Rabbit();
// The constructor needs to be fixed :)
KillerRabbit.prototype.constructor = KillerRabbit;
// Add your own sauce now!
KillerRabbit.prototype.kill = function(who) {
return this.eyes + "-eyed " + this.name + " killed: " + who;
}
// And now use it!
var caerbannog = new KillerRabbit("Vorpal", "Red");
// Some checks before killing anyone!
caerbannog instanceof Object; // true
caerbannog instanceof Rabbit; // true
caerbannog instanceof KillerRabbit; // true
// Unleash the rabbit!
caerbannog.speak("Hi!"); // "Vorpal says: Hi!"
caerbannog.kill("Churches"); // "Red-eyed Vorpal killed: Churches"
// Last check!
var roger = new Rabbit("Roger");
roger instanceof KillerRabbit; // false
// Applause!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment