gpt4 book ai didi

javascript - 如何将参数传递给对象文字中的函数

转载 作者:行者123 更新时间:2023-11-30 12:33:43 25 4
gpt4 key购买 nike

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

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

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.doSomething - 要调用的函数
  • 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。

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

How can I pass arguments to event handlers in jQuery?

关于javascript - 如何将参数传递给对象文字中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26792125/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com