Main Page

Multiple Inheritance support

The two highlighted lines in the previous code implement inheritance from the
Polygon
class for both
the
Triangle
and the
Rectangle
classes. The reason this works is that the
prototype
object isn’t being
overwritten when using the
inheritFrom()
method; methods are just being added to it. Using this
method, it’s possible to get around the prototype chaining restriction and implement dynamic prototyp-
ing the way it is intended.
Multiple Inheritance support
One of the most useful features of the zInherit library is its capability to support multiple inheritance,
which is not available using prototype chaining. Again, the key fact that makes this possible is that
inheritFrom()
doesn’t replace the
prototype
object.
The
inheritFrom()
method must be used in combination with object masquerading in order to inherit
properties and methods. Consider the following example:
function ClassX() {
this.messageX = “This is the X message. “;
if (typeof ClassX._initialized == “undefined”) {
ClassX.prototype.sayMessageX = function () {
alert(this.messageX);
};
ClassX._initialized = true;
}
}
function ClassY() {
this.messageY = “This is the Y message. “;
if (typeof ClassY._initialized == “undefined”) {
ClassY.prototype.sayMessageY = function () {
alert(this.messageY);
};
ClassY._initialized = true;
}
}
Both
ClassX
and
ClassY
are small classes, each with one property and one method. Suppose you now
have
ClassZ
that needs to inherit from both. The class can be defined like this:
function ClassZ() {
ClassX.apply(this);
ClassY.apply(this);
this.messageZ = “This is the Z message. “;
if (typeof ClassZ._initialized == “undefined”) {
ClassZ.prototype.inheritFrom(ClassX);
ClassZ.prototype.inheritFrom(ClassY);
119
Inheritance
07_579088 ch04.qxd 3/28/05 11:36 AM Page 119


JavaScript EditorFree JavaScript Editor     Ajax Editor


©