Object prototypes
An object prototype lets you specify a set of default values for an object. When an object property that has not been assigned a value is accessed, the prototype is consulted. If such a property exists in the prototype, its value is used for the object property.
Object prototypes are useful for two reasons: they ensure that all instances of an object use the same default values, and they conserve the amount of memory needed to run a script. When the two Rectangles, joe and sally, were created in the previous section, they were each assigned an area method. Memory was allocated for this function twice, even though the method is exactly the same in each instance. This redundant memory waste can be avoided by putting the shared function or property in an object's prototype. Then all instances of the object will use the same function instead of each using its own copy of it.
The following fragment shows how to create a Rectangle object with an area method in a prototype.
function rectangle_area()
{
return this.width * this.height;
}
function Rectangle(width, height)
{
this.width = width;
this.height = height;
}
Rectangle.prototype.area = rectangle_area;
The rectangle_area method can now be accessed as a method of any Rectangle object as shown in the following.
var area1 = joe.area();
var area2 = sally.area();
You can add methods and data to an object prototype at any time. The object class must be defined, but you do not have to create an instance of the object before assigning it prototype values. If you assign a method or data to an object prototype, all instances of that object are updated to include the prototype.
If you try to write to a property that was assigned through a prototype, a new variable will be created for the newly assigned value. This value will be used for the value of this instance of the object's property. All other instances of the object will still refer to the prototype for their values. If, for the sake of this example, we assume that joe is a special Rectangle, whose area is equal to three times its width plus half its height, we can modify joe as follows.
joe.area = function joe_area()
{
(this.width * 3) + (this.height/2);
}
This fragment creates a value, which in this case is a function, for joe.area that supercedes the prototype value. The property sally.area is still the default value defined by the prototype. The instance joe uses the new definition for its area method.