Basic Inheritance in JavaScript
//
// Function.extend( base )
// sets up inheritance between two constructor functions
// without needing to instantiate the base constructor
//
Function.prototype.extend = function( base )
{
// Define a surrogate constructor for base
var Temp = function(){}
Temp.prototype = base.prototype
// instantiate the surrogate
var t = new Temp()
t.constructor = this
// copy subclass prototype into surrogate object
for( key in this.prototype )
t[key] = this.prototype[key]
// set subclass prototype as the surrogate object
this.prototype = t
}
Example Usage
// Create a superclass called Animal
// Give its prototype a function called speak
function Animal(){}
Animal.prototype = {
sound : "",
speak : function(){ return this.sound; }
}
// Create animal types
function Cat(){ this.sound = "Meow" }
function Dog(){ this.sound = "Woof" }
// make Cat and Dog inherit from Animal
Cat.extend( Animal )
Dog.extend( Animal )
Outcome
// Create some instances
var cat = new Cat()
var dog = new Dog()
// Test out the inheritance
cat.speak() // Meow
dog.speak() // Woof
dog instanceof Animal // true
cat instanceof Animal // true
dog instanceof Cat // false