我正在尝试为对象中的每个函数添加一个钩子,以下是我的代码,它运行良好。
function foo(){}
foo.beforeMethodHook = function(){console.log('Hook was called.');}
foo.getInstance = function(){
var newInstance = new foo;
var funcNames = Object.getOwnPropertyNames(foo);
for(i in funcNames){
var funcName = funcNames[i];
if(funcName == 'getInstance' || funcName == 'beforeMethodHook' || Object.hasOwnProperty(funcName)) continue;
newInstance[funcName] = function (){
foo.beforeMethodHook();
return foo[this].apply(foo,arguments);
}.bind(funcName);
}
return newInstance;
}
foo.test1 = function(arg1){console.log('test1 was called. arg1 = ' + arg1);return true;}
foo.test2 = function(arg1,arg2){console.log('test2 was called. arg1 = ' + arg1 + ' , arg2 = ' + arg2);return true;}
//Test
var f = foo.getInstance();
f.test1('ahaha');
f.test2('heihei','houhou');
由于 IE10-不支持 function(){}.bind(),我尝试将 .bind() 更改为 (function(){})() 如下
newInstance[funcName] = (function (){
foo.beforeMethodHook();console.log(arguments);
return foo[funcName].apply(foo,arguments);
})(funcName);
但是问题来了,我失去了 f.test1('ahaha') 已经通过的论点。arguments 数组只给出 ["test1"] ,它是函数名。
我该如何解决?提前致谢。