Traditional Inheritance With Javascript
Javascript allows inheritance. It is however more complex than using when using traditional OOP languages with their built in extend functionality. There are really two ways to use inheritance within Javascript, traditional and prototypical. Here I will explain the traditional method. Though it is less memory efficient then the prototypical method, it is much more intuitive to those familiar with OOP.
The Prototype Object
You are probably familiar with Javascript’s prototype object. It is generally used to add methods to a Javascript object or class.
function Shape(color)
{
this.color = color;
}
Shape.prototype =
{
getColor: function()
{
return this.color;
}
}
The Prototype Chain
How the prototype chain works is, when a method is called on a object it first checks that object for the method and if it exists it is executed. If it is not found the object’s prototype object is checked. If the method is not found here the prototype object’s prototype is checked. This chain continues until either the method is found called or a prototype object is found to be null.
Using the Prototype Chain for Inheritance
How this chain provides inheritance is by setting the subclasses prototype object as an instance of the superclass. By doing this and then afterword setting the subclass’s constructor back to the subclass, you have added the super objects members to the subclass’s prototype. You also may want to call the superclasses constructor within the constructor, I have shown how to do this below. This is all done in the declaration of the subclass.
//our superclass
function Shape(color)
{
this.color = color;
}
Shape.prototype =
{
getColor: function()
{
return this.color;
}
}
//declare Circle’s constructor
function Circle(color, radius)
{
//call super constructor
Shape.call(this, color);
this.radius = radius;
}
//set Circle’s prototype to an instance of Shape
Circle.prototype = new Shape();
//set Circle’s constructor to Circle
Circle.prototype.constructor = Circle;
//add additional members to Circle’s prototype
Circle.prototype.getRadius = function()
{
return this.radius;
}
var aCircle = new Circle("red",10);
alert(aCircle.getColor());
alert(aCircle.getRadius());
Note
When adding to the subclasses prototype make sure not to do it as I have done below, because it overwrites the entire prototype object:
Circle.prototype =
{
...
}
Design Patterns.