Java Reference
In-Depth Information
The code in Listing 4-10 uses the
Point
constructor to create two objects and
calculates the distance between them.
Listing 4-10.
The Contents of the PointTest.js File
// PointTest.js
load("Point.js");
// Create two Point object, compute the distnce
// between them, and print the results
var p1 = new Point(100, 200);
var p2 = new Point(-100, -200);
var dist = p1.distance(p2);
printf("Distance between %s and %s is %.2f.", p1.toString(), p2.toString(),
dist);
Distance between Point(100, 200) and Point(-100, -200) is 447.21.
If you create a
Point
object, its prototype will automatically be set as
Point.prototype
object, so the new object will inherit the
toString
and
distance
methods. The following
snippet of code demonstrates this:
// Create two Point objects, compute and print the distnce between them
var p1 = new Point(100, 200);
var p2 = new Point(-100, -200);
var dist = p1.distance(p2);
printf("Distance between %s and %s is %.2f.", p1.toString(), p2.toString(),
dist);
Distance between Point(100, 200) and Point(-100, -200) is 447.21
Listing 4-11 contains the code for the
ColoredPoint
constructor. I will explain more
about this after the listing.
Listing 4-11.
The Contents of the ColoredPoint.js File
// ColoredPoint.js
load("Point.js");
function ColoredPoint(x, y, color) {
// Call the Point constructor function binding this,
// which is the current ColoredPoint object context
Search WWH ::
Custom Search