【问题标题】:Is there a way to wrap all JavaScript methods with a function?有没有办法用函数包装所有 JavaScript 方法?
【发布时间】:2011-04-24 13:33:11
【问题描述】:

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

func1(param1, param2)
func2(param1)
func3()
func4(param1, param2)

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

function globalBefore(func);
function globalAfter(func);

我已经为此搜索了很多,但似乎只有面向方面的解决方案需要您包装要记录的特定功能,或其他任何东西。我想要一些适用于全局范围内每个函数的东西(显然,除了它自己)。

【问题讨论】:

  • 你想包装对内置函数的调用(如window.alert),还是只是用户定义的函数?
  • 理想情况下,一切。我可以写一些东西来搜索、排序和过滤。

标签: javascript logging function aop word-wrap


【解决方案1】:

一个简单的方法是这样的

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];

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

【讨论】:

  • 很可爱,这足以让我开始。谢谢!
  • 如果您将全局范围的函数定义为function myFunction() { ... }var myFunction = function() { ... },这在IE8 或更低版本中不起作用(但在IE9 beta 中起作用!)因为它们不会被枚举。要使其在 IE8 或更低版本中运行,您需要将函数定义为 this.myFunction = function() { ... }window.myFunction = function() { ... }
  • @gilly,感谢您的提醒。我不知道这一点,很高兴知道..
【解决方案2】:

jquery-aop 可以解决问题吗?

【讨论】:

    【解决方案3】:

    也许你可以有一个函数,你可以将函数作为参数传递给它:

    function runner(func_to_run) {
        alert('about to run ' + func_to_run.name);
    
        func_to_run();
    
    }
    
    function test() {
        alert ('in test');
    }
    
    runner(test)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-30
      • 2013-09-20
      • 2012-10-11
      • 1970-01-01
      • 1970-01-01
      • 2011-10-01
      相关资源
      最近更新 更多