2011-12-28

Inheritance in JavaScript

JavaScript makes heavy use of objects, but its inheritance pattern is not like other object-oriented languages. Rather than class-based inheritance, JavaScript uses prototype-based inheritance. Objects are created by calling constructor functions with the new keyword. Every function has a prototype property that points to a prototype object. Any object instance has an implied reference to its prototype object (which may be null as well). Since the prototype is itself an ordinary object, it has a prototype too. This is what is called the prototype chain. When accessing a property of an object, the JavaScript engine tries to locate that property on the object itself. If it is not found on the object, it is searched in its prototype object and so forth.

The following code shows a simple example of using prototype-based inheritance.

var Shape = function () {};
Shape.prototype = Object.create(Object.prototype);
Shape.prototype.area = function () {
    throw new Error("Not implemented");
};

var Rectangle = function (width, height) {
    this.width = width;
    this.height = height;
};
Rectangle.prototype = Object.create(Shape.prototype);
Rectangle.prototype.area = function () {
    return this.width * this.height;
};

var Square = function (side) {
    Rectangle.apply(this, [side, side]);
};
Square.prototype = Object.create(Rectangle.prototype);

var square = new Square(16);
console.log(square.area()); // prints 256

No comments: