The classes we've shown in this chapter are all direct
subclasses of Object. This is typical of JavaScript programming;
there is not usually any need to produce a more complex class
hierarchy. When necessary, however, it is possible to subclass any
other class. For example, suppose we want to produce a subclass of
Complex in order to add some more methods. To do this, we simply have
to make sure that the prototype object of the new class is itself an
instance of Complex, so that it inherits all the properties of
Complex.prototype:
// This is the constructor for the subclass.
function MoreComplex(real, imaginary) {
this.x = real;
this.y = imaginary;
}
// We force its prototype to be a Complex object. This means that
// instances of our new class inherit from MoreComplex.prototype,
// which inherits from Complex.prototype, which inherits from
// Object.prototype.
MoreComplex.prototype = new Complex(0,0);
// Now add a new method or other new features to this subclass.
MoreComplex.prototype.swap = function( ) {
var tmp = this.x;
this.x = this.y;
this.y = tmp;
}
There is one subtle shortcoming to the subclassing technique shown
here. Since we explicitly set
MoreComplex.prototype to an object of our own
creation, we overwrite the prototype object provided by JavaScript
and discard the constructor property we are given.
This constructor property, described later in this
chapter, is supposed to refer to the constructor function that
created the object. A MoreComplex object, however,
inherits the constructor property of its
superclass, rather than having one of its own. One solution is to set
this property explicitly:
MoreComplex.prototype.constructor = MoreComplex;
Note, however, that in JavaScript 1.1, the
constructor property is read-only and cannot be
set in this way.