在對象裏定義了一個XMLHttpRequest請求了,怎麼在請求的回調中引用對象的『this』『神獸必讀』

問題

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 值。 */

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章