JavaScript中的prototypes(JavaScript: The Definitive Guide学习摘要7)

Prototypes:

All functions have a prototype property that is automatically created and
initialized when the function is defined. The initial value of the prototype
property is an object with a single property. This property is named
constructor and refers back to the constructor function with which the
prototype is associated. Any properties you add to this prototype object will
appear to be properties of objects initialized by the constructor.

This is clearer with an example. Here again is the Rectangle( ) constructor:

// The constructor function initializes those properties that
// will be different for each instance.
function Rectangle(w, h) {
this.width = w;
this.height = h;
}

// The prototype object holds methods and other properties that
// should be shared by each instance.
Rectangle.prototype.area = function( ) { return this.width * this.height; }

A constructor provides a name for a “class” of objects and initializes
properties, such as width and height, that may be different for each instance
of the class. The prototype object is associated with the constructor, and
each object initialized by the constructor inherits exactly the same set of
properties from the prototype. This means that the prototype object is an
ideal place for methods and other constant properties.

Note that inheritance occurs automatically as part of the process of looking
up a property value. Properties are not copied from the prototype object into
new objects; they merely appear as if they were properties of those objects.
This has two important implications. First, the use of prototype objects can
dramatically decrease the amount of memory required by each object because the
object can inherit many of its properties. The second implication is that an
object inherits properties even if they are added to its prototype after the
object is created. This means that it is possible (though not necessarily a
good idea) to add new methods to existing classes.

参见:

1.http://mckoss.com/jscript/object.htm

2.http://www.cs.rit.edu/~atk/JavaScript/manuals/jsobj/