更新时间:2022-12-12 22:57:35
简单的方法是像这样
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];
注释
仅处理全局函数,但你可以很容易地扩展它来处理特定的对象或方法等。
Notes
This handles only global functions, but you can easily extend it to handle specific objects or methods etc..