在方法中的 ajax 调用中使用“this”关键字的解决方案

Solution for using `this` keyword in ajax calls within methods?

本文关键字:this 关键字 解决方案 方法 ajax 调用      更新时间:2023-09-26

我正在创建一个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
         }
      });
   };
};