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

标签 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!
        }
    }
}

最佳答案

您可以使用函数的call 方法。

someFunction.call(objectToBeThis, argument1, argument2, andSoOnAndSoOn);

关于javascript - 如何在 Javascript 中重新定义 `this`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3920169/

相关文章:

javascript - 从其他 .js 文件访问函数

javascript 阻止 Twitter Bootstrap 选项卡链接激活

javascript - 在 module.exports 中调用函数的上下文安全方法是什么?

java - 这个()在Java中是什么意思

php - "Using $this when not in object context"出现在 Silex/phpunit 案例中

javascript - table thead 固定位置与顶栏

javascript - 将 Highcharts 转换为图像并使用ajax调用发送到服务器

javascript - 无法从 javascript 书中理解这些示例,好的部分

javascript - 专注于使用 TAB 键的 jQuery UI 日历可访问性

javascript - 如何删除事件处理程序 document.onkeydown?