Most of the time you will be referencing objects which are built-in to the DOM. However, you may want to create your own objects for storing data within a JavaScript program. There are several ways to create a new object, but we'll look at two:
Direct instance of an object simply means creating a new single object, such as point:
|
var point = new Object(); point.x = 45; point.y = -3; point.title = "Location"; |
Assigning a method to your new object is also simple. Assume that you already have coded a function named format, which returns a string representation of that object in the form title: x y. To assign this function as a method toString() of your object, use the syntax:
| point.toString = format; |
Sometimes, you'll want to create a "template" or prototype of an object. This does not create an actual instance of the object, but defines the structure of the object. In the future, then, you can quickly stamp out a particular instance of the object. Suppose that instead of point, you created a prototype object named Point. This object could then be a template for a particular point object. First, create a function which defines the object structure:
function Point(x, y, title)
{
this.x = x;
this.y = y;
this.title = title;
this.toString = function()
{
return(title + ": " + x + " " + y);
}
}
|
As soon as the Point prototype has been set, you can quickly create single instances of that object by using the keyword new:
|
var p1 = new Point(3, -6, "Location"); var p2 = new Point(0, 0, "Origin"); |
By creating the object instances, it is perfectly legal not to pass one or more tailing parameters to its constructor. This is a general rule by calling any JavaScript function. Thus, the following code
|
var p = new Point(5, 3); document.write(p.toString()); // document.write(p); // alternative code |
produces the output undefined: 5 3.