Objects and Prototypes |
Active Web |
A server-side script object is an unordered collection of properties each with zero or more attributes. Properties are containers that hold other objects, primitive values or functions.
Script objects are created by constructors that initialise the object by assigning initial values to the properties. The constructors are themselves objects with properties. Each constructor has a prototype property that is used to implement prototype-based inheritance and shared properties. Objects are created by using constructors in 'new' expressions; for example, new String("A String") creates a String object.
Server-side script supports prototype-based inheritance. Every constructor has an associated prototype, and every object created by that constructor has a property that refers to its prototype object. Furthermore each prototype has a property that refers to its prototype object, and so on. This is called the prototype chain. When a reference is made to a property in an object, the reference returned is for the first property of that name in the prototype chain. In other words if the property is not found in the object, then it is looked for in the next object in the prototype chain, and so on, until the end of the chain.
Because a constructor only has a single reference to its prototype object all objects created by the constructor have the same prototype. This means that if a property is put in a prototype then that property is immediately shared by all existing objects, and any subsequently created objects that have that prototype in their chain.
The example above shows the prototype links. The constructor object has been used to create three new objects. Each of the new objects has been given a reference to the prototype that the constructor has a reference to. That prototype has a reference to another prototype, and so on. The properties x1 and x2 in each object are private and separate but the property a1 in the prototype is shared by all the new objects as is the property a2. The constructors property p1 is private to the constructor object. This example does not show the end of the prototype chain as it continues from Prototype Object 2.
Topic ID: 150077