如何在对象文字中向函数传递参数

How to pass arguments to a function within an object literal

本文关键字:函数 参数 对象 文字      更新时间:2023-09-26

我在对象文字中有很多代码,有几个函数我希望能够为参数传递函数参数,但我不知道如何做到这一点。

这是我的对象的一个例子。。

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'));

有什么想法吗?还是我的做法不对?

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.dotSomething-要调用的函数
  • null-将在其中调用函数的上下文。通过提供null,我们表示使用其"正常"上下文
  • arg1-被调用函数的param1形式参数的值
  • arg2-被调用函数的param2形式参数的值

由于click回调提供了最终参数(事件),该参数已经提供,不需要额外或显式声明。传递附加参数时,jQuery.proxy()会传递形式参数列表前面处的参数,而隐式提供的任何剩余参数都会在最后传递。因此,如果我们有一个函数,看起来像:

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。

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

如何在jQuery中将参数传递给事件处理程序?