Main Page

Inheritance

function Polygon(iSides) {
this.sides = iSides;
}
Polygon.prototype.getArea = function () {
return 0;
};
function Triangle(iBase, iHeight) {
Polygon.call(this, 3);
this.base = iBase;
this.height = iHeight;
}
Triangle.prototype.inheritFrom(Polygon);
Triangle.prototype.getArea = function () {
return 0.5 * this.base * this.height;
};
function Rectangle(iLength, iWidth) {
Polygon.call(this, 4);
this.length = iLength;
this.width = iWidth;
}
Rectangle.prototype.inheritFrom(Polygon);
Rectangle.prototype.getArea = function () {
return this.length * this.width;
};
To test this code, you can use the same example as before and add in a couple extra lines to test out the
instanceOf()
method:
var triangle = new Triangle(12, 4);
var rectangle = new Rectangle(22, 10);
alert(triangle.sides);
alert(triangle.getArea());
alert(rectangle.sides);
alert(rectangle.getArea());
alert(triangle.instanceOf(Triangle)); //outputs “true”
alert(triangle.instanceOf(Polygon)); //outputs “true”
alert(rectangle.instanceOf(Rectangle)); //outputs “true”
alert(rectangle.instanceOf(Polygon)); //outputs “true”
The last four lines test
instanceOf()
and should all return
true
.
117
Inheritance
07_579088 ch04.qxd 3/28/05 11:36 AM Page 117


JavaScript EditorFree JavaScript Editor     Ajax Editor


©