Is There A Way To Wrap All Javascript Methods With A Function?
I want to wrap every function call with some logging code. Something that would produce output like: func1(param1, param2) func2(param1) func3() func4(param1, param2) Ideally, I
Solution 1:
A simple approach would be something like this
var functionPool = {} // create a variable to hold the original versions of the functionsfor( var func inwindow ) // 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 namevar functionName = func;
window[functionName] = function(){ // overwrite the function with our own versionvar args = [].splice.call(arguments,0); // convert arguments to array// do the logging before callling the methodconsole.log('logging: ' + functionName + '('+args.join(',')+')');
// call the original method but in the window scope, and return the resultsreturn functionPool[functionName].apply(window, args );
// additional logging could take place here if we stored the return value ..
}
})();
}
}
To undo you would need to run the
for (funcin functionPool)
window[func] = functionPool[func];
Notes This handles only global functions, but you can easily extend it to handle specific objects or methods etc..
Solution 2:
jquery-aop might do the trick?
Solution 3:
Maybe you could have a function to which you pass the function to execute as a parameter:
function runner(func_to_run) {
alert('about to run ' + func_to_run.name);
func_to_run();
}
function test() {
alert ('in test');
}
runner(test)
Post a Comment for "Is There A Way To Wrap All Javascript Methods With A Function?"