在方法中的 ajax 调用中使用“this”关键字的解决方案
Solution for using `this` keyword in ajax calls within methods?
我正在创建一个JavaScript类。某些方法包含使用 JQuery 的 AJAX 调用。我遇到的问题是,由于范围的变化,我无法在 AJAX 回调中使用 this
关键字。我已经想出了一个黑客解决方案,但我想知道解决这个问题的最佳实践方法是什么?
下面是一个示例:
var someClass = function() {
var someElement = $('form');
this.close = function() {
someElement.remove();
};
this.query = function() {
$.ajax({
url: someurl,
success: function() {
this.close(); // does not work because `this` is no longer the parent class
}
});
};
};
只需使用 context
参数将您想要的任何对象传递给成功回调:
$.ajax({
url: someurl,
context: this,
success: function() {
this.close(); // this is what it was when we triggered the AJAX call
}
});
您还可以传递复杂的对象和内容:
$.ajax({
url: someurl,
context: { foo: 'bar', element: this },
success: function() {
alert(this.foo);
this.element.close();
}
});
我更喜欢使用匿名函数,因为您可以获得局部变量,并且您不必使用我在代码块中间发现笨拙的var
创建变量。
var someClass = function() {
var someElement = $('form');
this.close = function() {
someElement.remove();
};
this.query = function() {
(function(self, someurl){
$.ajax({
url: someurl,
success: function() {
self.close();
}
});
}(this, someurl));
};
};
在此示例中,没有必要将someurl
作为参数包含在内,但是,当您想要制作全局变量的局部副本时,它会派上用场,这些全局变量可能会在等待响应时更改值。
存储对this
的引用 - 我的约定是使用 self
.
var someClass = function() {
var self = this, //<--- store a reference
someElement = $('form');
this.close = function() {
someElement.remove();
};
this.query = function() {
$.ajax({
url: someurl,
success: function() {
self.close(); // does not work because `this` is no longer the parent class
}
});
};
};
相关文章:
- JavaScript 中的嵌套函数和 “this” 关键字
- Javascript 对象和 this 关键字
- 将“this”关键字发送到对象中
- 如何使用“this”关键字来调用a
- 组合类和事件监听器:`this`关键字
- 将this关键字与selectedIndex一起使用的优势
- 在forEach中调用类函数:Javascript如何处理“this”关键字
- 使用“this”关键字响应类行为
- Javascript 'this' 关键字 在嵌套函数中
- 事件处理函数不适用于“this”关键字
- (无效)如何在 JSON 中使用“this”关键字
- JavaScript Promise 和 this 关键字
- 如何在 html 中使用“this”关键字在对象上调用方法
- Javascript中“this”关键字的目的是什么?
- 处理 jQuery 事件时在 JavaScript 类中覆盖的 'this' 关键字
- PHP 相当于 JavaScript “this” 关键字,特别是在对象中
- 嵌套函数中“this”关键字的范围
- 在我的命名空间JavaScript中使用this关键字
- JavaScript 中的 'this' 关键字
- Javascript [this] 关键字绑定与 new