Thursday, December 30, 2010

Prototype in javaScript

Prototype is a prebuilt object  in javascript (introduced in version 1.1) which makes it possible to add one or more properties/methods in a single or all instances of an object (both types of object - prebuilt and custom).
Case 1: Below is the example to add custom property to single instance only:
//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
Case 2: We have to use prototype keyword to apply a property to all instances of an object Below is an example:
//First, create the custom object "circle"
function circle(){
}
circle.prototype.pi=3.14159
// create the object method
function alertmessage(){
alert(this.pi)
}
circle.prototype.alertpi=alertmessage

Now, all instances of circle() now has the pi property prebuilt into them. Also, all instances of the circle object contain a alertmessage() method!

case 3: Extending functionality to the pre-built string() object
We can use the prototype object on any custom objects. But, it is not for prebuilt object only. Javascript allows us to "prototype" prebuilt objects that are created with the new keyword like string object, image object, Array object, date object.

<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 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:
!etis ym ot emocleW
yad lufituaeb a si yadoT
Web Development and Design Foundations with XHTML (5th Edition)

Real example of prototype object feature of javascript. Following is the function which is used to trim spaces.
String.prototype.trim = function ()
{
return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

No comments:

Post a Comment

Thanks for your valuable comments.

Important queries based formulas to watch performance of a MySQL based application

(1) Session Vs global status variables value select G.variable_name,G.variable_value GlobalValue,S.variable_value SessionValue from (selec...