访问变量时出错

时间:2013-08-09 08:21:38

标签: javascript xmlhttprequest

尝试使用我的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”未定义。 你知道为什么我不能访问这个属性吗?

1 个答案:

答案 0 :(得分:0)

致电时

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

this未引用您的MyObject instanciated。它引用您声明并分配给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){}
},