从事件侦听器返回一个变量

问题描述

| 我有一个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.html
this.xml
中的变化。但是,我从未看到过这种变化,并且意识到了原因。 在匿名侦听器函数内部,这是指匿名函数,而不是“ 4” 我希望找到解决此问题的方法,以某种方式使xml和文本响应从侦听器函数中移入
XMLRequest
函数的
this.xml
和ѭ2,中,以便我可以对其进行监视 有什么办法可以做到吗? - 编辑 - 布拉德的例子,经我的编辑,供讨论:
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\"
    

解决方法

        在使用它们之前,请先存储所需的变量,然后对其进行引用(通常可以这样做,以避免出现范围问题:
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();
    

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...