Example 12-7. Creating a Superclass
// Create a Circle (superclass) constructor
function Circle( ) {
this.area = function ( ) { return Math.PI * this.radius * this.radius; };
}
// Create our usual Ball class constructor
function Ball ( radius, color, xPosition, yPosition ) {
this.radius = radius;
this.color = color;
this.xPosition = xPosition;
this.yPosition = yPosition;
}
// Here we make the superclass by assigning an instance of Circle to
// the Ball class constructor's prototype
Ball.prototype = new Circle( );
// Now let's make an instance of Ball and check its properties
myBall = new Ball ( 16, 0x445599, 34, 5);
trace(myBall.xPosition); // 34, a normal property of Ball
trace(myBall.area( )); // 804.24..., area( ) was inherited from Circle
However, our class hierarchy now has poor
structure -- Ball defines
radius, but radius is actually
a property common to all circles, so it belongs in our
Circle class. The same is true of
xPosition and yPosition. To fix
the structure, we'll move radius,
xPosition, and yPosition to
Circle, leaving only color in
Ball. (For the sake of the example, we'll
treat color as a property only balls can have.)
Conceptually, here's the setup of our revised
Circle and Ball
constructors:
// Create the Circle (superclass) constructor
function Circle ( radius, xPosition, yPosition ) {
this.area = function ( ) { return Math.PI * this.radius * this.radius; };
this.radius = radius;
this.xPosition = xPosition;
this.yPosition = yPosition;
}
// Create the Ball class constructor
function Ball ( color ) {
this.color = color;
}
Having moved the properties around, we're faced with a new
problem. How can we provide values for radius,
xPosition, and yPosition when
we're creating objects using Ball and not
Circle ? We have to make one more adjustment to
our Ball constructor code. First, we set up
Ball to receive all the required properties as
parameters:
function Ball ( color, radius, xPosition, yPosition ) {
Next, within our Ball constructor, we define the
Circle constructor as a method of the
ball object being instantiated:
this.superClass = Circle;
Finally, we invoke the Circle constructor on the
ball object, and pass it values for
radius, xPosition, and
yPosition:
this.superClass(radius, xPosition, yPosition);