Inheritance in JavaScript

Sources for Information

Great, great Q&A on prototypes (and therefore inheritance). READ THIS FIRST!

Very long and in-depth article on OOP in JavaScript including data types, constructors, prototypes, inheritance, and properties.

This StackOverflow answer has a very good description of Prototype inheritance and Closure inheritance.

Defining a Sub-Class

The standard paradigm, is to use the prototype chain to implement the inheritance of methods from a super class. Any methods defined on the sub-class will supersede those defined on the super-class.

function A() {                     // Define super class
	this.x = 1;
}
 	
A.prototype.DoIt = function() {    // Define Method
	this.x += 1;
}
 	
function B() {
	A.call(this);                   // Call super-class constructor (if desired)
	this.y = 2;
}
B.prototype = new A;               // Define sub-class
B.prototype.constructor = B;
 	
B.prototype.DoIt = function() {    // Define Method
	A.prototype.DoIt.call(this);    // Call super-class method (if desired)
	this.y += 1;
}

// instantiate and test 	
b = new B;
 	
document.write((b instanceof A) + ', ' + (b instanceof B) + '<BR/>'); //true, true
b.DoIt();
document.write(b.x + ', ' + b.y); //2, 3

Something to keep in mind is that each time a sub-class is defined, we explicitly call the constructor of the super-class in order to insert it into our prototype chain. So it is important to ensure that no undesirable side-effects will occur when this call is made. Conversely, if the super-class constructor should be called for each instance of every sub-class, code must be explicitly added to the sub-class's constructor to make this call (as is done in the above example).

Example

For a working example (similar to the above code), check out the Prototypes page.

Here's another example:

var Pet = function(name) {
	this.name = name;
	this.sound = "silence";
}
Pet.prototype.makeSound = function() {
	alert(this.name + " says " + this.sound);
}
var Cat = function(name, sound) {
	Pet.call(this, name);
	this.sound = sound;
}
Cat.prototype = new Pet;
Cat.prototype.constructor = Cat;
Cat.prototype.purr = function () {
	alert('purr, purr');
}

var maria = new Cat("Maria", "meow");
maria.makeSound();
maria.purr();