Javascript Prototype

Javascript prototype is very useful thing. Say, we want to perform some sort of transformation or something else on string  like we want to find some pattern matching for validation. Example below is based on this.

Requires: Javascript


<script type="text/javascript">
String.prototype.found = null;        
var str = new String('my string');
function findpat(str)
   var gotcha =;
   if(gotcha > 0 )
       return true;
       return false;
var ret = findpat(str);
str.found = ret;

Line 2: We created a prototype object for string named found and equate it to null.
Line 3: We create str as String.
Line 7: Then in the code below it we find the pattern ‘str’ insensitive of case.
Line 17: Then we gave value to ‘found’ which can be used further.

  • Line 3 is important here as prototype for String is given, so str = ‘my string’ will not work. We have to declare it as String type. Same is to be done if it is being used with other type or custom types.