Putting things into perspective- Examples

If you're having a hard time staying awake while reading this tutorial, I can't say I blame you. The prototype object of JavaScript isn't exactly as flashy and fun to learn as say, document.bgColor or, and the rewards aren't always instant. But if you're at all interested in extending JavaScript and creating your own objects and libraries, the prototype object is a must learn. Allow me to show you now a couple of practical examples on using the prototype object of JavaScript:

-Example 1-Extending functionality to the pre-built string() object

As mentioned earlier in this tutorial, the prototype object can be used on pre-built JavaScript objects created with the new keyword to add custom properties/ methods to them. Let's see an interesting example on how to extend the prebuilt String object of JavaScript to include a method that writes any string backwards when called upon:

<script type="text/javascript">

/*code for extending String object with method that writes text backwards*/

//core custom method for writing text backwards
function outputbackwards(){
	for (i=this.length-1;i>=0;i--)

//Attach custom method to string object


The above code may not look like much, but it just added a whole new functionality to the default string object- the ability to output any text backwards! Here are a few examples:

<script type="text/javascript">
var message1="Welcome to my site!"
var message2="Today is a beautiful day"


We're playing Frankenstein with the JavaScript language!

-Example 2-Extending functionality to a custom JavaScript object

For the most part, you'll probably be using the prototype object to extend and expand a custom JavaScript object you created earlier. JavaScript developers who create custom objects often know that the traditional way of assigning custom properties/ methods to an object isn't exactly a walk in the park (See "Creating Custom objects in JavaScript"). With the prototype object at hand, however, this process becomes a lot simpler and intuitive.

I'll quickly demonstrate the concept by first creating a "dummy object", and using the prototype object- and only this object- to equip the dummy object with properties and methods:

<script type="text/javascript">

//create dummy object
function dummy(){

//Create custom property
function dummyproperty(){

//Create custom method
function dummymethod(){



The key to take away from this example is how easy it is to attach a property/ method to an object (so it's reflected on all instances of it)- by using the prototype object of JavaScript.