我想使用 $.proxy 在点击事件上加载函数。 如果我使用下面的单击事件加载该函数,那么一切正常。
点击事件正在运行
$('element').click($.proxy(this.doProcess, this));
点击事件不起作用
$('element').click(function(){
// Perform other things
$.proxy(this.doProcess, this);
});
正如您所看到的,我想在加载函数之前对单击事件执行其他操作。您能帮我弄清楚为什么如果我使用“.click(function()...”而不是简单地使用“.click()..”则无法加载
最佳答案
因为在第一个片段中,单击函数调用返回的函数。在第二个代码片段中,您将当前的 this
值绑定(bind)到该函数,但不调用返回的函数。您可以使用调用运算符 (()
) 来调用该函数:
$.proxy(this.doProcess, this)();
请注意,匿名函数(即当前事件处理程序)上下文中的 this
并不引用外部上下文的 this
关键字的值,您可以可以缓存值:
var that = this;
$('element').click(function() {
// Perform other things
$.proxy(that.doProcess, this)(/* arguments go here */);
// | |
// | ----- refers to the clicked element
// ----- reference of the outer context's `this` value
});
关于javascript - 使用 $.proxy javascript 调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26940796/