2013-01-23 49 views
0

我有一個類(你好),這個類有foo屬性,這個屬性必須在xhr請求後填充。如何設置fooXMLHttpRequest以及如何調用afterLoad()XMLHttpRequest和類屬性

function Hello(){ 

    this.foo = null; 

    this.process = function(){ 
     var req = new XMLHttpRequest(); 
     req.open('GET', 'http://some.url', true); 
     req.onload = function(){ 
      // How to set Hello.foo in this context? 
      // And how to call Hello.afterLoad() from this context? 
      // this == XMLHttpRequest instance 
     }; 
     req.send(null); 
    } 
    this.afterLoad = function(){ 
     console.log(this.foo); 
     // Some stuff goes here 
    } 
} 
+0

爲什麼不利用這個JS框架?像jquery – Cybermaxs

+1

[像這樣?](http://stackoverflow.com/questions/5648028/jquery-use-a-variable-outside-the-function) – ClydeFrog

+2

你嘗試使用像'var that = this這樣的助手嗎?在聲明過程函數並像'that.foo ='whateva''一樣訪問它之前? – Kevkong

回答

1
function Hello(){ 

    this.foo = null; 

    this.process = function(){ 
    var _that = this, 
     req = new XMLHttpRequest(); 
    req.open('GET', 'http://some.url', true); 
    req.onload = function(){ 
     // How to set Hello.foo in this context? 
     // And how to call Hello.afterLoad() from this context? 
     // this == XMLHttpRequest instance 
     _that.foo = 'something'; 
     _that.afterLoad(); 
    }; 
    req.send(null); 
    } 
    this.afterLoad = function(){ 
    console.log(this.foo); 
    // Some stuff goes here 
    } 
} 
+0

哦!謝謝!其作品。 – korzhyk