Javascript 试图使用;这";不必使用;那";将函数作为参数传递给jquery委托事件处理程序时

Javascript 试图使用;这";不必使用;那";将函数作为参数传递给jquery委托事件处理程序时,javascript,parameters,this,keyword,Javascript,Parameters,This,Keyword,假设我有一些javascript,我成功地将两个事件处理程序附加到DOM无序列表中的所有DOM“li”元素: function userClickFunction() { console.log("USER CLICK"); clickFunction(this);//had to pass "this" as parameter } function autoClickFunction() { console.log("AUTO CLICK"); clickFu

假设我有一些javascript,我成功地将两个事件处理程序附加到DOM无序列表中的所有DOM“li”元素:

function userClickFunction() {
    console.log("USER CLICK");
    clickFunction(this);//had to pass "this" as parameter
}
function autoClickFunction() {
    console.log("AUTO CLICK");
    clickFunction(this);//had to pass "this" as parameter
}
function clickFunction(that) {
    var clickedItem = $(that).attr('id');//using "that" I was able to get the attrs from the "li" element
    console.log("CLICKED!");
}
$("#my_list").delegate("li", "click", userClickFunction);
$("#my_list").delegate("li", "autoClick", autoClickFunction);
然后我在JS的其他地方触发这些事件处理程序

$("#some_li").trigger('click');//just kidding, the user does this :P
$("#some_li").trigger('autoClick');//fired by comparing some elaborate timers and interesting state variables.
我只是想知道是否有一个更优雅的解决方案不必使用“that”以及函数clickFunction()中的“this”实际上指的是什么?是否有其他方法可以引用调用函数的上下文而不必将其作为参数传递?
谢谢大家!

您可以在调用函数时使用下面的方法传递自定义上下文,然后在回调函数中使用
this

function userClickFunction() {
    console.log("USER CLICK");
    clickFunction.call(this); //had to pass "this" as parameter
}

function autoClickFunction() {
    console.log("AUTO CLICK");
    clickFunction.call(this); //had to pass "this" as parameter
}

function clickFunction() {
    var clickedItem = this.id; //now this refers to the `li` element, also to get the `id` just refer to `this.id` no need to call `attr()`
    console.log("CLICKED!");