回调函数中'this'的值

Tom*_*tor 4 javascript ajax

我有这个代码用于对webservice执行ajax请求:

var MyCode = {
    req: new XMLHttpRequest(), // firefox only at the moment

    service_url: "http://url/to/Service.asmx",

    sayhello: function() {
        if (this.req.readyState == 4 || this.req.readyState == 0) {
            this.req.open("POST", this.service_url + '/HelloWorld', true);
            this.req.setRequestHeader('Content-Type','application/json; charset=utf-8');
            this.req.onreadystatechange = this.handleReceive; 
            var param = '{}';
            this.req.send(param);
        }
    },

    handleReceive: function() {
        if (this.req.readyState == 4) {
            // todo: using eval for json is dangerous
            var response = eval("(" + this.req.responseText + ")");
            alert(response);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

它当然是用MyCode.sayhello()调用的.

它的问题是handleReceive函数的第一行"req未定义".它确实被调用了4次,所以我知道上面的代码将请求发送到服务器.

我怎么解决这个问题?

cgp*_*cgp 5

经典封闭问题.当你得到回调时,闭包实际上已经引用了HTTP对象.

您可以按照某人的建议执行以下操作:

var that = this;
this.req.onreadystatechange = function() { this.handleReceive.apply(that, []); };
Run Code Online (Sandbox Code Playgroud)

或者只是执行以下操作:

var that = this;
this.req.onreadystatechange = function() { that.handleReceive(); };
Run Code Online (Sandbox Code Playgroud)