Java Reference
In-Depth Information
// as this for the Point invocation, so the x and y
// properties will be added to the current ColoredPoint object
Point.call(this, x, y);
// Add a color property to the new object
this.color = color;
};
// Set a new object whose prototype is Point.prototype as
// the prototype for the ColoredPoint function
ColoredPoint.prototype = Object.create(Point.prototype);
// Set the constructor property of the prototype
ColoredPoint.prototype.constructor = ColoredPoint;
// Override the toString() method of the Point.prototype object
ColoredPoint.prototype.toString = function() {
return "ColoredPoint(" + this.x + ", " + this.y + ", " + this.color + ")";
};
First, the code loads the Point.js file that contains the definition of the Point
constructor function.
The first statement in the ColoredPoint constructor calls the Point() function
passing the x and y arguments. It is important to understand the intention of this
statement. It is the same as calling the superclass constructor in Java from the subclass
constructor. You are in the process of creating a ColoredPoint object and you want to
call the Point function as the constructor, so the ColoredPoint object being created is
initialized as a Point first. You may be tempted to use Point(x, y) instead of Point.
call(this, x, y) . However, that will not work. The confusion comes from the meaning
of the keyword this . When you call the Point() function from the ColoredPoint
function, you need to point the keyword this in the Point() function to the new
ColoredPoint object being created. When you call Point(x, y) , the keyword this
inside the Point() function points to the global object, not the ColoredPoint object
being created. The call() method of a function lets you pass the this reference as
the first argument. In this case, you passed the this reference that is available in the
ColorPoint() function, so the Point() function executes in the same context as the
ColoredPoint function. The statements this.x = x and this.y = y inside the Point()
function will add x and y properties to the new ColoredPoint object.
 
Search WWH ::




Custom Search