我有一个函数,它是一个 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/