↑
Main Page
Alternative Inheritance Paradigms
Polygon.call(this, 3);
this.base = iBase;
this.height = iHeight;
if (typeof Triangle._initialized == “undefined”) {
Triangle.prototype = new Polygon();
Triangle.prototype.getArea = function () {
return 0.5 * this.base * this.height;
};
Triangle._initialized = true;
}
}
The previous code illustrates both
Polygon
and
Triangle
defined using dynamic prototyping. The mis-
take is in the highlighted line, where
Triangle.prototype
is set. Logically, this is the correct location;
but functionally, it doesn’t work. Technically, by the time that code is run, the object is already instanti-
ated and tied to the original
prototype
object. Although changes to that prototype object are reflected
properly with very late binding, replacing the
prototype
object has no effect on that object. Only future
object instances reflect the change, making the first instance incorrect.
To correctly use dynamic prototyping with inheritance, you must assign the new
prototype
object out-
side of the constructor, like this:
function Triangle(iBase, iHeight) {
Polygon.call(this, 3);
this.base = iBase;
this.height = iHeight;
if (typeof Triangle._initialized == “undefined”) {
Triangle.prototype.getArea = function () {
return 0.5 * this.base * this.height;
};
Triangle._initialized = true;
}
}
Triangle.prototype = new Polygon();
This code works because the
prototype
object is assigned before any objects are instantiated.
Unfortunately, this means the code isn’t completely encapsulated in the constructor, which is the main
purpose of dynamic prototyping.
Alternative Inheritance Paradigms
Due to the limitations of ECMAScript inheritance (for instance, lack of a private scope and the inability
to easily access superclass methods), developers around the world have constantly pushed their code to
115
Inheritance
07_579088 ch04.qxd 3/28/05 11:36 AM Page 115
Free JavaScript Editor
Ajax Editor
©
→