Let's move the code that takes care of all of the inheritance details from the last example into a reusable extend()
function:
function extend(Child, Parent) { var F = function () {}; F.prototype = Parent.prototype; Child.prototype = new F(); Child.prototype.constructor = Child; Child.uber = Parent.prototype; }
Using this function (or your own custom version of it) helps you keep your code clean with regard to the repetitive inheritance-related tasks. This way you can inherit by simply using:
extend(TwoDShape, Shape);
and
extend(Triangle, TwoDShape);
Let's see a complete example:
// inheritance helper function extend(Child, Parent) { var F = function () {}; F.prototype = Parent.prototype; Child.prototype = new F(); Child.prototype.constructor = Child; Child.uber = Parent.prototype; } // define -> augment function Shape() {} Shape.prototype.name = 'Shape'; Shape.prototype.toString = function () { return this.constructor.uber ? this.constructor.uber.toString() + ', ' + this.name : this.name; }; // define -> inherit -> augment function TwoDShape() {} extend(TwoDShape, Shape); TwoDShape.prototype.name = '2D shape'; // define function Triangle(side, height) { this.side = side; this.height = height; } // inherit extend(Triangle, TwoDShape); // augment Triangle.prototype.name = 'Triangle'; Triangle.prototype.getArea = function () { return this.side * this.height / 2; };
Testing:
> new Triangle().toString();
"Shape, 2D shape, Triangle"
13.59.36.203