XMLHttpRequest和类属性

时间:2013-01-23 12:57:51

标签: javascript ajax class attributes xmlhttprequest

我有一个类(Hello),这个类有foo属性,这个属性必须在xhr请求后填充。如何设置foo XMLHttpRequest以及如何致电afterLoad()

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
    }
}

1 个答案:

答案 0 :(得分: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
  }
}