调用Javascript函数时,如何设置自定义值"this"?

Cha*_*les 5 javascript jquery this javascript-events

我正在使用jQuery,并且我有一个用作事件回调的函数,因此在该函数中"this"表示捕获事件的对象.但是,有一个实例,我想从另一个函数显式调用该函数 - 在这种情况下如何设置"this"在函数内相等?

例如:

function handleEvent(event) {
    $(this).removeClass("sad").addClass("happy");
}

$("a.sad").click(handleEvent); // in this case, "this" is the anchor clicked

function differentEvent(event) {
    $("input.sad").keydown(e) {
        doSomeOtherProcessing();
        handleEvent(e); // in this case, "this" will be the window object
                        // but I'd like to set it to be, say, the input in question
    }
}
Run Code Online (Sandbox Code Playgroud)

Pat*_*ney 12

使用 应用 打电话.

handleEvent.call(this, e);
Run Code Online (Sandbox Code Playgroud)

  • 替代方法:使用call(),它与apply()完全相同,除了传递一系列参数而不是参数数组.(https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Function/call) (3认同)