Java Reference
In-Depth Information
Now, you need to set up the prototype chain for objects that will be created using
the ColoredPoint function. This is done by setting the prototype property of the
ColoredPoint function to an object whose prototype is Point.prototype . The Object.
create() function does this, like so:
// Set a new object whose prototype is Point.prototype as the prototype for the
// ColoredPoint function
ColoredPoint.prototype = Object.create(Point.prototype);
The statement replaced the prototype property of the ColoredPoint function
that will also reset the constructor property of the prototype property. The following
statement restores the constructor property:
// Set the constructor property of the prototype
ColoredPoint.prototype.constructor = ColoredPoint;
ColoredPoint objects will inherit the toString() method from Point.prototype .
To make sure that a ColoredPoint returns its color component when the toString()
method is called on it. To achieve this, you override the toString() method, as shown:
// Override the toString() method of the Point.prototype object
ColoredPoint.prototype.toString = function() {
return "ColoredPoint(" + this.x + ", " + this.y + ", " + this.color + ")";
};
Listing 4-12 shows the code that tests the Point and ColoredPoint functions. It
creates an object of each type and computes the distance between them. Finally, the
results are printed.
Listing 4-12. The Contents of the ColoredPointTest.js File
// ColoredPointTest.js
load("Point.js");
load("ColoredPoint.js")
// Create a Point and a ColoredPoint objects
var p1 = new Point(100, 200);
var p2 = new ColoredPoint(25, 50, "blue");
// Compute the distance between two points
var p1Top2 = p1.distance(p2);
var p2Top1 = p2.distance(p1);
printf("Distance of %s from %s = %.2f", p1.toString(), p2.toString(), p1Top2);
printf("Distance of %s from %s = %.2f", p2.toString(), p1.toString(), p2Top1);
 
Search WWH ::




Custom Search