Custom Search

Prototype Function in JavaScript

Prototype function is a part of scripting language commonly used is EcmaScript i.e. JavaScript and Flash Action Script programming. It allows you to override the existing functionality of the objects methods and also allows you to add new methods to the existing in-build JavaScript Objects.





Example 1 - Adding New Method to Existing Object

<script language="javascript">
String.prototype.divide = function()
{
   var x=this;
   return x.split(" ");
}
var str_data = "Hello World";
var test = str_data.divide();
alert(test);
</script>

Explanation of Example1
Here i am adding divide() method to the String Object using prototype function. The main functionality of the divide method is to split the string data by space. So after executing this example script i will get output “Hello, World” as the return type will be Array.

Example 2 - OverRide existing Object Methods Functionality:

<script language="javascript">
String.prototype.substr = function()
{
   var x=this;
   return x.split(" ");
}
var str_data = "Hello World";
var test = str_data.substr();
alert(test);
</script>

Explanation of Example2:
We all know substr function will return you the part of string as per the index position specified. Now here in example i have modified the functionality of the substr function to split the string by space.

NOTE on Prototype Function:
Prototype Function does not permanently adds new methods to existing JavaScript Object it is only available till the time you provide the prototype function for an object.

Custom Search

Related Post

Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to my feed and get articles like this delivered automatically to your feed reader.

Comments

No comments yet.

Leave a comment

(required)

(required)