我们有一个使用jQuery的胖客户端应用程序,并希望使用firebug的console.profile API来分析代码的性能 . 问题是,我不想更改代码来编写配置文件语句 . 举个例子:
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();
我想描述我的instance.ajax方法,但我不想在代码中添加配置文件语句,因为这使得维护代码变得困难 .
我正在尝试使用闭包覆盖方法,如下所示:http://www.novogeek.com/post/2010/02/27/Overriding-jQueryJavaScript-functions-using-closures.aspx但我不太确定如何实现 . 有关于此的任何指示?我认为这将有助于许多大型项目轻松地分析代码,而无需对代码进行大的更改 .
这是个主意 . 只需在firebug控制台中运行以下代码,就可以知道我想要实现的目标 .
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());
});
现在我需要的是,如果我说instance.ajax(),我想要调用新的ajax()方法,以及console.profile语句 . 希望我清楚这个要求 . 请即兴发布上述代码 .
此致,克里希纳,http://www.novogeek.com
2 回答
如果您只想修改“搜索”的单个实例,那么这应该有效:
我知道这是很久以前的事了,但我想补充一下,以防其他人找到这个答案 . 您可以通过为每个函数添加名称来使匿名/私有函数工作 . 其他评论提到手动操作我想解释如何:
$('.stuff').each(function() { ... });
至
$('.stuff').each(function workOnStuff() { ... });