Similar to the “constructor” property that was reviewed in the first tutorial, every object constructor exposes a special property called “prototype.” But what is the function of this property? Well, it will allow you to add properties (and methods) to all objects instantiated from that constructor function. Maybe this sounds a little confusing, so allow me to illustrate this concept by an easy example. Have a look at the constructor function below:
Here, I’ve used the constructor function that you saw in the first tutorial, which comes in handy for building up DIV elements on the fly and appending them to the document tree. After defining the above function, what I’ll do next is use the “prototype” property for assigning a new property to the constructor function, and then create two div objects from the same constructor. Please take a look at the following example:
Div.prototype.margin='2px'; var div1=new Div(300,250,100,100,5,'00f'); div1.display(); alert(div1.margin); // returns ‘2px’ var div2=new Div(200,150,50,50,5,'0ff'); div2.display(); alert(div2.margin); // returns ‘2px’
As I said before, I’ve assigned a new “margin” property to all DIV objects, by using the “prototype” property. Doing so, all the subsequent objects created (or not) from the same constructor will also expose the “margin” property, as the above example demonstrates. Even when this property wasn’t specifically declared inside the constructor function, the corresponding “alert()” methods will display the same property value for each DIV object, instantiated from the same constructor.
As you can see, the “prototype” property allows you to specify object properties outside the constructor function, which will be shared by all the objects instantiated from this function. This condition brings us to an important point for establishing a hierarchical relationship between objects: by using this property, it’s possible to create a base constructor function that contains some basic properties and methods, and then define different objects that inherit (and eventually override) all the properties defined in the base object.