Java Reference
In-Depth Information
// Call toString() method on the log object
print(log.toString());
function log(str) {
print(new Date() + ": " + str);
}
Every function in Nashorn has a property named
prototype
, which is another object.
Do not confuse the
prototype
property of a function with the prototype object (or simply
prototype) of the function. The
prototype
property of a function is set automatically as
the prototype for all objects created using that function as a constructor. The
prototype
property has a property named
constructor
that refers back to the function itself.
Listing 4-9 creates a constructor function called
Point
and adds two methods named
toString()
and
distance()
to its
prototype
property.
Listing 4-9.
The Contents of the Point.js File
// Point.js
// Define the Point constructor
function Point(x, y) {
this.x = x;
this.y = y;
}
// Override the toString() method in Object.prototype
Point.prototype.toString = function() {
return "Point(" + this.x + ", " + this.y + ")";
};
// Define a new method called distance()
Point.prototype.distance = function(otherPoint) {
var dx = this.x - otherPoint.x;
var dy = this.y - otherPoint.y;
var dist = Math.sqrt(dx * dx + dy * dy);
return dist;
};
Search WWH ::
Custom Search