
The JavaScript Language
|
19
allows instances of your class to be converted to strings. For
example:
// Define function literals and assign them
// to properties of the prototype object.
Point.prototype.distanceTo = function(that) {
var dx = this.x - that.x;
var dy = this.y - that.y;
return Math.sqrt(dx*dx + dy*dy);
}
Point.prototype.toString = function () {
return '(' + this.x + ',' + this.y + ')';
}
If you want to define static (or class) methods or properties,
you can assign them directly to the constructor function,
rather than to the prototype object. For example:
// Define a commonly used Point constant
Point.ORIGIN = new Point(0,0);
The preceding code fragments define a simple Point class
that we can use with code like this:
// Call constructor to create a new Point object
var p = new Point(3,4);
// Invoke a method of the object, using a static
// property as the argument.
var d = p.distanceTo(Point.ORIGIN);
// Adding the object to a string implicitly
// invokes toString().
var msg = "Distance to " + p + " is " + d;
Regular Expressions
JavaScript supports regular expressions for pattern matching
with the same syntax as the Perl programming language.
JavaScript 1.2 supports Perl 4 regular expressions, and Java-
Script 1.5 adds supports for some of the additional features
of Perl 5 regular expressions. A regular expression is speci-
fied literally in a JavaScript program as a sequence of charac-
ters within ...