The prototype object of JavaScript
No, we're not going to discuss how to construct a new version of JavaScript in this tutorial. The prototype object of JavaScript, introduced starting in JavaScript 1.1, is a prebuilt object that simplifies the process of adding custom properties/ methods to all instances of an object. I know, I'm starting to sound a little geeky already, but hay, JavaScript isn't just about fun and games...it's important to learn the serious side of it too.
A little background first...
In JavaScript, you're allowed to add custom properties to both prebuilt and custom objects. Here's an example of each:
//adding a custom property to a prebuilt object var myimage=new Image() myimage.size="26k" /*adding a custom property to the custom object "circle"*/ //First, create the custom object "circle" function circle(){ } var smallcircle=new circle() smallcircle.pi=3.14159
A custom property added this way only exists for that instance of the object. If I were to spit out another instance of circle(), called "bigcircle", for example, bigcircle.pi would by default return "undefined" until I go over the process again of first defining bigcircle.pi, as with smallcircle.
There are times when you'll want to add a custom property that's only reflected on a particular instance of an object, and times, when you just wished all instances of the object would recognize the custom property already. For example, all circles- and not just small circles- have a pi, so it's reasonable to assume you'd like the custom property "pi" added in a way so that it's default across all instances of the circle object. That's where the prototype object of JavaScript comes in.