如何在Javascript中重新定义`this`?

Bil*_*eal 5 javascript jquery this

我有一个函数,它是一个JQuery事件处理程序.因为它是一个JQuery事件处理程序,所以它使用该this变量来引用调用它的对象(对于该库来说是正常的).

不幸的是,我需要在此时手动调用该方法.如何this在被调用函数内部进行操作,就像从JQuery调用一样?

示例代码:

function performAjaxRequest() {
    //Function which builds AJAX request in terms of "this"
}

function buildForm(dialogOfForm) {
    var inputItem;
    dialogOfForm.html('...');
    dialogOfForm.dialog('option', 'buttons', {
        "Ok" : performAjaxRequest
    });
    inputItem = dialogOfForm.children(':not(label)');
    //Redirect enter to submit the form
    inputItem.keypress(function (e) {
        if (e.which === 13) {
            performAjaxRequest(); //Note that 'this' isn't the dialog box
                                  //as performAjaxRequest expects here, it's
                                  //the input element where the user pressed
                                  //enter!
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Chu*_*uck 12

您可以使用该函数的call方法.

someFunction.call(objectToBeThis, argument1, argument2, andSoOnAndSoOn);
Run Code Online (Sandbox Code Playgroud)


Sea*_*ira 8

如果dialog是您需要设置的对象this:

performAjaxRequest.apply(dialog, []); 
// arguments (instead of []) might be even better
Run Code Online (Sandbox Code Playgroud)

应该做的伎俩.

否则,在jQuery中,您只需trigger在要设置的元素上调用该方法即可this

例如,假设您希望click在按钮上发生事件,并且您现在需要它发生.只需致电:

$("#my_button").trigger("click");
Run Code Online (Sandbox Code Playgroud)

#my_buttonclick处理程序将被调用,this并将被设置为该#my_button元素.

如果你需要调用一个不同的方法this...例如,this参考jQuery对象本身,那么你将需要使用callapply在你的函数上.

Chuck和meder已经给你了每个例子...但是把所有东西放在一个地方:

// Call
my_function.call(object_to_use_for_this, argument1, argument2, ... argumentN);

// Apply
my_function.apply(object_to_use_for_this, arguments_array);
Run Code Online (Sandbox Code Playgroud)

看看:一个名单除了结合的情况