有没有办法用一个函数包装所有 JavaScript 方法? [英] Is there a way to wrap all JavaScript methods with a function?

查看:40
本文介绍了有没有办法用一个函数包装所有 JavaScript 方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

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

Ideally, I would like an API of the form:

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

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

I've googled quite a bit for this, but it seems like there's only aspect-oriented solutions that require you to wrap the specific functions you want to log, or whatever. I want something that applies to every function in the global scope (except itself, obviously).

推荐答案

一个简单的方法是这样的

A simple approach would be something like this

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..

这篇关于有没有办法用一个函数包装所有 JavaScript 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆