有没有办法用函数包装所有JavaScript方法?

bla*_*086 12 javascript logging aop function word-wrap

我想用一些日志代码包装每个函数调用.会产生输出的东西,如:

func1(param1, param2)
func2(param1)
func3()
func4(param1, param2)
Run Code Online (Sandbox Code Playgroud)

理想情况下,我想要一个形式的API:

function globalBefore(func);
function globalAfter(func);
Run Code Online (Sandbox Code Playgroud)

我已经搜索了相当多的内容,但似乎只有面向方面的解决方案需要你包装你想要记录的特定功能,或者其他什么.我想要一些适用于全局范围内的每个函数的东西(显然除了它本身).

Gab*_*oli 10

一个简单的方法就是这样

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 ..
        }
      })();
  }
}
Run Code Online (Sandbox Code Playgroud)

要撤消你需要运行

for (func in functionPool)
  window[func] = functionPool[func];
Run Code Online (Sandbox Code Playgroud)

Notes
仅处理全局函数,但您可以轻松扩展它以处理特定对象或方法等.