What is really fascinating about JavaScript is it’s dynamic nature. You can dynamically change the behaviour of the code… even not your code. While this is really powerful, it can be also a pain if not used with care.

Well, let’s do something practical now. I want to intercept every log message in my js application. As people usually use Firebug (and if you’re not using it… well, you should, so start right here), the javascript code is populated with console.log or console.warn messages. Say we want to execute a function before and after console.log is called. Test the following code within firebug.

var backup = console.log;

function beforeLog(){
    backup('before log:',arguments);
}

function afterLog(){
    backup('after log:',arguments);
}

console.log = function(){
    beforeLog.apply(this,arguments);
    backup.apply(this,arguments);
    afterLog.apply(this,arguments);
}

console.log('hello','world');

In the first place, make a backup to the function we want to intercept.

Second, just redefine the function… and we usually want to execute the old function (so here is where we need the backup) and perform some additional things as well. Placing the code at the beginning of your coolest app changes the behaviour of all the log messages you have.

I found this useful when going from a development environment to a live environment. The best choice would be to use a build system to comment out (or even better, delete) all the console.log() calls. But a quick fix when going live is the following:

if (!window.console){
   /*
    * for users who do not have firebug installed, 
    * just define a "mock" console object
    */
    window.console = {};
}
window.console.log = function(){};
console.log('hello world'); // call to an empty function

This is just a simple use of dynamically changing the behaviour of existing code. What about you? How do you intercept function calls? Waiting for some nice suggestions.