Archive for April 27th, 2011

Wednesday, April 27th, 2011

In Javascript, we can add our own custom methods to Javascript’s global classes during runtime.

String, Date, Array, Boolean, Math, Number are some of the JS classes. Every class has its own built-in methods. Like, “String” Class has toLowerCase(), indexOf(), etc
“Date” class has getTime(), getDay(), getFullYear(), etc.
“Array” class has pop(), sort(), etc…

We can add our custom methods during runtime using keyword “prototype”

For eg: If I want to add a method “myCurrency” to the “Number” class.

Number.prototype.myCurrency= function(){

        var price  = this.valueOf();

        return currencySymbol + price;

var price = 20; alert (price.myCurrency());

Result: $20

Eg 2: If I want to add a custom method “detail” to “Array” class. From that method, I need to get the length of the array, first element & last elements value.

Array.prototype.detail= function(){
        return "Length = " + this.length + ", First Element = " + this[0] + ", Last Element = " + return [this.length-1];

var myArray = ["iSense","Prowareness","Prabhu"];; alert (myArray.detail());

Result: Length = 3, First Element = iSense, Last Element = Prowareness

Download code

Enjoy Coding 🙂