【问题标题】:How to pass arguments to a function within an object literal如何将参数传递给对象字面量中的函数
【发布时间】:2014-11-07 00:41:24
【问题描述】:

我在一个对象字面量中有很多代码,并且有几个函数我希望能够为参数传递函数参数,但我不知道该怎么做。

这是我的对象的一个​​例子..

var test = {
    button: $('.button'),
    init: function() {
        test.button.on('click', this.doSomething);
    },
    doSomething: function(event, param1, param2) {
        console.log(param1);
        console.log(param2);
    }
};

因此,当单击按钮并调用函数doSomething 时,我想传入param1param2 的参数。

可能有类似的东西,但这不起作用。

test.button.on('click', this.doSomething('click', 'arg1', 'arg2'));

有什么想法,或者我是不是走错了路?

【问题讨论】:

  • 感谢@TysonWolker,效果很好!
  • @TysonWolker 该解决方案既好又优雅,但假设可以修改 doSomething 函数以以这种方式使用它。如果目标函数已经被指定或编码为接受三个参数并且我们想要保留这个概念怎么办?
  • 然后可能使用 $.proxy 作为其他答案提到的。

标签: javascript jquery object-literal


【解决方案1】:

jQuery.proxy() 函数似乎正是您所需要的。好好阅读文档,看看它们是否对您有意义。对于您的具体示例,

var test = {
    button: $('.button'),
    init: function() {
        test.button.on('click', $.proxy(this.doSomething, null, 'arg1', 'arg2');
    },
    doSomething: function(param1, param2, event) {
        console.log(param1);
        console.log(param2);
    }
};

在本例中,$.proxy 的参数为:

  • this.doSomething - 要调用的函数
  • null - 调用函数的上下文。通过提供 null,我们是说使用它的“正常”上下文。
  • arg1 - 被调用函数的param1形参的值
  • arg2 - 被调用函数的param2形参的值

由于click 回调提供了最终参数(事件),该参数已经提供,不需要额外或显式声明。 jQuery.proxy() 在传递附加参数时传递形式参数列表的 front 中的那些,并且隐式提供的任何剩余参数都在末尾传递。所以如果我们的函数看起来像:

var f = function(a, b, c) {
    console.log(a, b, c);
};

并通过代理调用它:

var p = $.proxy(f, null, 2, 3);
p(1);

记录的 a、b 和 c 的值将是 2,3,1。

这个问题也非常接近这个问题。

How can I pass arguments to event handlers in jQuery?

【讨论】:

  • 无法在文档中找到它的解释。我确定它不会起作用。
  • @zerkms 你能澄清评论吗? jQuery.proxy() 的链接不起作用吗?关于它的文档,我们有什么可以进一步讨论的吗?
  • 我确信建议的解决方案没有实现正确的部分应用程序。见jsfiddle.net/qwwc1qwj
  • @zerkms 太棒了。很棒的收获。我弄错了参数的顺序并更新了答案。非常感谢我的朋友。 +1
  • 如果 jquery 像 lodash 那样支持右偏应用就好了:lodash.com/docs#partialRight
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-31
  • 2013-09-21
  • 1970-01-01
相关资源
最近更新 更多