【问题标题】:XMLHttpRequest inside an object: how to keep the reference to "this"对象内的 XMLHttpRequest:如何保持对“this”的引用
【发布时间】:2010-05-11 05:41:50
【问题描述】:

我从一个 javascript 对象内部进行了一些 Ajax 调用。:

myObject.prototye = {
  ajax: function() {
    this.foo = 1;

    var req = new XMLHttpRequest();
    req.open('GET', url, true);
    req.onreadystatechange = function (aEvt) {  
      if (req.readyState == 4) {  
        if(req.status == 200)  {
          alert(this.foo); // reference to this is lost
        }
      }
  }
};

在 onreadystatechange 函数内部,this 不再引用主对象,所以我无权访问 this.foo。我可以在 XMLHttpRequest 事件中保留对主要对象的引用吗?

【问题讨论】:

    标签: javascript ajax


    【解决方案1】:

    最简单的方法通常是将this 的值存储在一个局部变量中:

    myObject.prototype = {
      ajax: function (url) { // (url argument missing ?)
        var instance = this; // <-- store reference to the `this` value
        this.foo = 1;
    
        var req = new XMLHttpRequest();
        req.open('GET', url, true);
        req.onreadystatechange = function (aEvt) {  
          if (req.readyState == 4) {  
            if (req.status == 200)  {
              alert(instance.foo); // <-- use the reference
            }
          }
        };
      }
    };
    

    我还怀疑您的 myObject 标识符确实是 constructor function(您正在分配 prototype 属性)。

    如果是这种情况,请不要忘记包含正确的 constructor 属性(因为您要替换整个 prototype),它只是对构造函数的引用。

    可能与此问题无关,但建议阅读:

    【讨论】:

      【解决方案2】:

      另一个简单的解决方案是将您的 onreadystatechange 函数绑定到此。 bind -ing 该函数的作用与 CMS 的答案基本相同(即,将值添加到闭包中),但 bind 以透明的方式进行:您继续使用 this 而不是设置 @ 987654327@变量。

      如果您的代码库不包含 Function#bind 实现,那么这里是一个:

      Function.prototype.bind = function(obj) {
          var __method = this;
          var args = []; for(var i=1; i<arguments.length; i++) args.push(arguments[i]);
          return function() {
              var args2 = []; for(var i=0; i<arguments.length; i++) args2.push(arguments[i]);
              return __method.apply(obj, args.concat(args2));
          };
      }
      

      您可以在代码中使用它:

      myObject.prototype = {
        ajax: function() {
          this.foo = 1;
      
          var req = new XMLHttpRequest();
          req.open('GET', url, true);
          req.onreadystatechange = function (aEvt) {  
            if (req.readyState == 4) {  
              if(req.status == 200)  {
                alert(this.foo); // reference to this is *kept*
              }
            }
          }.bind(this) // <- only change
        }
      };
      

      【讨论】:

      • 我强烈建议在创建 Function.prototype.bind 方法之前检查它是否存在,因为它是 ECMAScript 第 5 版标准的一部分,并且它正在被所有主要浏览器供应商实现,很快就会成为原生实现将可用,并且您不想用自己的方法覆盖它:WebKit、Mozilla、Google V8。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-19
      • 1970-01-01
      • 1970-01-01
      • 2013-05-16
      相关资源
      最近更新 更多