↑
Main Page
Dynamic prototyping support
Dynamic prototyping support
As mentioned earlier, prototype chaining can’t be used in the true spirit of dynamic prototyping, which
is to keep all code for a class inside of its constructor. The zInherit library fixes this problem by allowing
the
inheritFrom()
method to be called from inside the constructor.
Take a look at the polygon dynamic prototyping example used earlier, now with the addition of the
zInherit library:
function Polygon(iSides) {
this.sides = iSides;
if (typeof Polygon._initialized == “undefined”) {
Polygon.prototype.getArea = function () {
return 0;
};
Polygon._initialized = true;
}
}
function Triangle(iBase, iHeight) {
Polygon.call(this, 3);
this.base = iBase;
this.height = iHeight;
if (typeof Triangle._initialized == “undefined”) {
Triangle.prototype.inheritFrom(Polygon);
Triangle.prototype.getArea = function () {
return 0.5 * this.base * this.height;
};
Triangle._initialized = true;
}
}
function Rectangle(iLength, iWidth) {
Polygon.call(this, 4);
this.length = iLength;
this.width = iWidth;
if (typeof Rectangle._initialized == “undefined”) {
Rectangle.prototype.inheritFrom(Polygon);
Rectangle.prototype.getArea = function () {
return this.length * this.width;
};
Rectangle._initialized = true;
}
}
118
Chapter 4
07_579088 ch04.qxd 3/28/05 11:36 AM Page 118
Free JavaScript Editor
Ajax Editor
©
→