从事件侦听器返回变量

时间:2011-06-04 05:41:23

标签: javascript

我有XMLHttpRequests的通用函数。如下:

function XMLRequest(address, data){
    this.html = "null";
    this.xml = null;
    this.stat = null;
    req = new XMLHttpRequest();

    req.addEventListener('readystatechange', function(this) {

        console.log("from event listener, this.html = "+this.html);
        this.ready = req.readyState;
        if(req.readyState == 4)
        {
            this.stat = req.readyState;
            if(req.status == 200)
            {
                try{
                    this.xml = req.responseXML.documentElement;
                }
                catch(err){
                    this.xml = err;
                }

                try{
                    this.html = req.responseText;
                }catch(err){
                    this.html = err;
                }
                console.log("html = "+this.html);
            }
        }   
    }, false);

    req.open("GET", address+"?"+data, true);
    req.setRequestHeader('content-type', "text/xml");
    req.send();    
    return this;

};

我认为我会使用watch()功能来监视this.htmlthis.xml中的更改。但是,我从未见过这种变化,我意识到了原因;

在匿名侦听器函数内部,这是指匿名函数,而不是XMLRequest

我希望找到解决方法,以某种方式获得xml&文本响应超出了监听器功能并进入this.xml& this.html函数的XMLRequest,以便我可以观察它

我有什么方法可以做到吗?

- 编辑 -

布拉德的例子,我的编辑,供讨论:

function MyObject(){
    this.publicFoo = 'BAR';
    var privateFoo = 'bar';

    var self = this; // store current context so we can reference it in other scopes.
    this.CallMe = function(){
        self.publicFoo = 'newBAR';
        setTimeout(function(){
            alert('public: ' + self.publicFoo + '\nprivate: ' + privateFoo);
        },100);
    };

    return this;
};

var myobj = MyObject();
myobj.CallMe();
alert(myobj.publicFoo)  <-- I want this to alert "newBAR", not "BAR"

1 个答案:

答案 0 :(得分:2)

在使用之前存储您需要的变量,然后引用它们(正如您通常所做的那样,以避免范围问题:

function MyObject(){
    this.publicFoo = 'BAR';
    var privateFoo = 'bar';

    this.CallMe = function(){
        // set them as something referenceable when not within the object's scope
        var iSee_publicFoo = this.publicFoo,
            iSee_privateFoo = privateFoo;

        setTimeout(function(){
            alert('public: ' + iSee_publicFoo + '\nprivate: ' + iSee_privateFoo);
        },100);
    };

    return this;
};

var myobj = MyObject();
myobj.CallMe();

使用var self = this版本:

function MyObject(){
    this.publicFoo = 'BAR';
    var privateFoo = 'bar';

    var self = this; // store current context so we can reference it in other scopes.
    this.CallMe = function(){
        setTimeout(function(){
            alert('public: ' + self.publicFoo + '\nprivate: ' + privateFoo);
        },100);
    };

    return this;
};

var myobj = MyObject();
myobj.CallMe();