Wednesday, August 20, 2008

Overidding a javascript method

As I'm forced to spend more time doing client web development, I'm finding javascript to be an interesting language to work. Recently I've discovered a fun way to override a method on a javascript object that I would like to share.

Let's take the following example:

function apple(color)


{


this._color=color;


}



apple.prototype.AlertColor=function()


{


alert(this._color);


}



var myApp=new apple("red");


myApp.AlertColor();




When you run this inside a web page you'll get an alert box with the color red. Now let's pretend that our apple is an external script, which is used in many web pages; however, in one specific page we need to change the functionality of the AlertColor method. How do we do this?


apple.prototype.AlertColor=function()


{


alert("blue");


}



var myApp=new apple("red");


myApp.AlertColor();




What we are doing here is replacing the definition of AlertColor on all instances of apple with our new function. Running this script will give you an alert of blue. Let us go one step further and pretend that we want to wrap custom functionality around the AlertColor function.


apple.prototype.Original_AlertColor=apple.prototype.AlertColor;



apple.prototype.AlertColor=function()


{


alert("You are asking about the color well I am...");


this.Original_AlertColor();


}



var myApp=new apple("red");


myApp.AlertColor();




Here you will get two alert boxes. What we have essentially done is add a new function called Orginal_AlertColor and we set to the orginal AlertColor function. Then with our new function we call the original function.

Now that hopefully we understand the basic how to, what can I do with this? Here are some examples I've found in the wild:
  • TextBoxWatermark Extender in Ajax Control toolkit uses this approach to replace the default ASP.Net function for submitting a form. They use this to blank out the watermarked text before posting back to the server.
  • Component Art recommends using this to replace the standard window.alert() method which they use to spit out debug information.

Enjoy!

No comments: