2013-01-23 50 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