1.6 Object-Oriented JavaScript
JavaScript objects are associative arrays that associate values with
named properties. JavaScript provides a simple inheritance mechanism,
and it is possible to define new classes of objects for use in your
own programs. To define a new class, start by writing a constructor
function. A constructor is like any other function, except it is
invoked with the new operator and it uses the
this keyword to refer to and initialize the newly
created object. For example, here is a constructor to create objects
of a new class named Point.
function Point(x,y) { // Constructor for Point
this.x = x; // Initialize X coordinate
this.y = y; // Initialize Y coordinate
}
Every JavaScript function used as a constructor has a property named
prototype. This property refers to a special
prototype object for the class of objects created by the constructor.
Any properties you define on this prototype object are inherited by
all objects created with the constructor function. The prototype
object is commonly used to make methods available to all instances of
a class. Defining a method named toString 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;
|