我想用一些日志记录代码包装每个函数调用。会产生如下输出的东西:
func1(param1, param2)
func2(param1)
func3()
func4(param1, param2)
理想情况下,我想要以下形式的 API:
function globalBefore(func);
function globalAfter(func);
我为此在 google 上搜索了很多,但似乎只有面向方面的解决方案要求您包装要记录的特定功能或其他任何内容。我想要适用于全局范围内每个函数的东西(显然除了它本身)。
最佳答案
一个简单的方法是这样的
var functionPool = {} // create a variable to hold the original versions of the functions
for( var func in window ) // scan all items in window scope
{
if (typeof(window[func]) === 'function') // if item is a function
{
functionPool[func] = window[func]; // store the original to our global pool
(function(){ // create an closure to maintain function name
var functionName = func;
window[functionName] = function(){ // overwrite the function with our own version
var args = [].splice.call(arguments,0); // convert arguments to array
// do the logging before callling the method
console.log('logging: ' + functionName + '('+args.join(',')+')');
// call the original method but in the window scope, and return the results
return functionPool[functionName].apply(window, args );
// additional logging could take place here if we stored the return value ..
}
})();
}
}
要撤销你需要运行
for (func in functionPool)
window[func] = functionPool[func];
注意事项
这只处理全局函数,但您可以轻松地扩展它来处理特定的对象或方法等。
关于javascript - 有没有办法用一个函数包装所有的 JavaScript 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3919134/