Add console.profile statements to JavaScript/jQuery code on the fly
<p>We have a thick client app using jQuery heavily and want to profile the performance of the code using firebug's console.profile API. The problem is, I don't want to change the code to write the profile statements. Take this example:</p>

<pre>
var search=function(){
    this.init=function(){
        console.log('init');
    }
    this.ajax=function(){
        console.log('ajax');
        //make ajax call using $.ajax and do some DOM manipulations here..
    }
    this.cache=function(){
        console.log('cache');
    }
}
var instance=new search();
instance.ajax();
</pre>

<p>I want to profile my instance.ajax method, but I dont want to add profile statements in the code, as that makes it difficult to maintain the code.</p>

<p>I'm trying to override the methods using closures, like this: <a href="http://www.novogeek.com/post/2010/02/27/Overriding-jQueryJavaScript-functions-using-closures.aspx" rel="nofollow">http://www.novogeek.com/post/2010/02/27/Overriding-jQueryJavaScript-functions-using-closures.aspx</a> but am not very sure how I can achieve. Any pointers on this? I think this would help many big projects to profile the code easily without a big change in code.</p>

<p>Here is the idea. Just run the below code in firebug console, to know what I'm trying to achieve. </p>

<pre>
var search=function(){
    this.init=function(){
        console.log('init');
    }
    this.ajax=function(){
        console.log('ajax');
        //make ajax call using $.ajax and do some DOM manipulations here..
    }
    this.cache=function(){
        console.log('cache');
    }
}
var instance=new search();

$.each(instance, function(functionName, functionBody){
    (function(){
        var dup=functionBody
        functionBody=function(){
            console.log('modifying the old function: ',functionName);
            console.profile(functionName);
            dup.apply(this,arguments);
            console.profileEnd(functionName);
        }
    })();
    console.log(functionName, '::', functionBody());
});
</pre>

<p>Now what I need is, if i say instance.ajax(), I want the new ajax() method to be called, along with the console.profile statements. Hope I'm clear with the requirement. Please improvise the above code.</p>

<p>Regards,
Krishna,
<a href="http://www.novogeek.com" rel="nofollow">http://www.novogeek.com</a> </p>
