Categories:

Using the prototype object to add custom properties to objects

The prototype object is here to help when you wish to quickly add a custom property to an object that is reflected on all instances of it. To use this object, simply reference the keyword "prototype" on the object before adding the custom property to it, and this property is instantly attached to all instances of the object. A demonstration is worth a thousand words, so I'll show one right now: Let's define the custom property "pi" in the above in a way so it's a default property of all instances of circle():

//First, create the custom object "circle"
function circle(){
}
circle.prototype.pi=3.14159

Having done the above, all instances of circle() now has the pi property prebuilt into them.

There is an important thing to take note at this point in the tutorial. While you are free to use the prototype object on any custom objects, this is NOT the case with prebuilt ones (such as image, string etc). JavaScript only allows you to "prototype" prebuilt objects that are created with the new keyword, such as the following:

  • The image object
  • The string object
  • The date object
  • The Array object

In the final part of this tutorial, I'll demonstrate an example involving prototyping a prebuilt JavaScript object.

Let's move on to see how to use the prototype object to add custom methods.