如何获得一个回调函数的所有参数 [英] How to get all arguments of a callback function

查看:196
本文介绍了如何获得一个回调函数的所有参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很多时候,我发现自己使用的回调函数,我没有它的文档方便,它会很高兴地看到所有这一切都意味着要传递给回调函数的参数。

  //回调是,我不知道该ARGS功能...
//并让说,它被定义等中使用:回调(名称,数量,价值)
something.doSomething(回调);

我怎么能确定的ARG的传球到了吗?

请注意:当code本身是模糊和缩小的查看源$ C ​​$ C可能是无益的(因为许多JS框架是)


解决方案

要获取的参数列表不破坏功能,覆盖回调函数是这样的:

  VAR原=回调;
回调函数=(){
    //使用参数的东西:
    的console.log(参数);
    返回original.apply(这一点,参数);
};


  1. 的背景下, 这个 为preserved。

  2. 所有参数都正确地传递。

  3. 的返回值正确地传递。

请注意:此方法在大多数情况下。虽然有优势情况下,这种方法就会失效,其中包括:


  • 只读属性(假例如,使用 Object.defineProperty 可写的定义)
  • 正在使用getter / setter方法​​定义时的getter / setter不是对称的属性。

  • 主机对象和插件的API:例如闪存和ActiveX。

Very often, I find myself using a callback function and I don't have its documentation handy, and it would be nice to see all of the arguments that are meant to be passed to that callback function.

// callback is a function that I don't know the args for...
// and lets say it was defined to be used like: callback(name, number, value)
something.doSomething( callback );

How can I determine what args its passing into that?

Note: looking at the source code can be unhelpful when the code itself is obfuscated and minified (as many js frameworks are)

解决方案

To get the list of arguments without breaking functionality, overwrite the callback function in this way:

var original = callback;
callback = function() {
    // Do something with arguments:
    console.log(arguments);
    return original.apply(this, arguments);
};

  1. The context, this is preserved.
  2. All arguments are correctly passed.
  3. The return value is correctly passed.

NOTE: This method works in most cases. Though there are edge cases where this method will fail, including:

  • Read-only properties (e.g. defined using Object.defineProperty with writable:false)
  • Properties that are defined using getters/setters, when the getter/setter is not symmetric.
  • Host objects and plugin APIs: E.g. Flash and ActiveX.

这篇关于如何获得一个回调函数的所有参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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