Categories:

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 window.open, 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--)
		document.write(this.charAt(i))
}

//Attach custom method to string object
String.prototype.writeback=outputbackwards

</script>

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!"
message1.writeback()
var message2="Today is a beautiful day"
message2.writeback()
</script>

Output:

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(){
}

dummy.prototype.prop=dummyproperty
dummy.prototype.method=dummymethod

</script>

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.