0

尝试使用我的 xmlhttprequest 访问变量时遇到问题。我有以下代码:

function MyObject(){
    this.variable = 0;
}

MyObject.prototype = {
    request: function(url, call_function){
        try{
            if(window.XMLHttpRequest)
                httpRequest = new XMLHttpRequest();
            else if(window.ActiveXObject)
                httpRequest = new ActiveXObject("Microsoft.XMLHTTP");

            httpRequest.onreadystatechange = function(data)
            {
                try
                {
                    if(httpRequest.readyState == 4)
                    {
                        if(httpRequest.status == 200){
                            var tab = JSON.parse(httpRequest.responseText).childs;
                            call_function.apply(this, Array(tab));
                        } 
                    }
                }
                catch(e){}
            };
            httpRequest.open('GET', url);
            httpRequest.send();
        }
        catch(err){}
    },

    start: function(url){
        this.request(url, this.func);
    },

    func: function(){
        try{this.variable = 5;}
        catch(err){alert(err);}
    }
};

var obj = new MyObject();
obj.start(url);

使用此代码,当程序执行“func”函数时,它会捕获一个异常,并告诉我“this.variable”未定义。你知道为什么我不能访问这个属性吗?

4

1 回答 1

0

你打电话时

call_function.apply(this, Array(tab));

this没有引用您的 MyObject 实例化。它指的是您声明并分配给 onreadystatechange 事件的函数。您需要保存对对象的引用:

request: function(url, call_function){
    try{
        var self = this;
        if(window.XMLHttpRequest)
            httpRequest = new XMLHttpRequest();
        else if(window.ActiveXObject)
            httpRequest = new ActiveXObject("Microsoft.XMLHTTP");

        httpRequest.onreadystatechange = function(data)
        {
            try
            {
                if(httpRequest.readyState == 4)
                {
                    if(httpRequest.status == 200){
                        var tab = JSON.parse(httpRequest.responseText).childs;
                        call_function.apply(self, Array(tab));
                    } 
                }
            }
            catch(e){}
        };
        httpRequest.open('GET', url);
        httpRequest.send();
    }
    catch(err){}
},
于 2013-08-09T08:25:25.890 回答