欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

在对象里定义了一个XMLHttpRequest请求了,怎么在请求的回调中引用对象的『this』『神兽必读』...

程序员文章站 2022-05-24 18:22:40
...

问题

XMLHttpRequest inside an object: how to keep the reference to “this”

且看代码

javascriptmyObject.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变量了,有什么办法可以在这个回调中继续引用主对象呢

答案

最简单的办法就是将主对象的this保存到局部变量中,

javascriptmyObject.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属性(设置)恢复为myObject

附,在<<JavaScript设计模式>>看到的译者注:
/*
*译者注:定义一个构造函数时,其默认的prototype对象是一个Object 类型的实例,其constructor属性会被自动设置
*为该构造函数本身。如果手工将其prototype 设置为另外一个对象,那么新对象自然不会具有原对象的constructor值,
*所以需要重新设置其constructor 值。
*/