小编Rad*_*u M的帖子

javascript类在内部调用XMLHttpRequest,然后处理onreadystatechange

这件事几乎有效:

function myClass(url) {

this.source = url;
this.rq = null;
this.someOtherProperty = "hello";

// open connection to the ajax server
this.start = function() {
    if (window.XMLHttpRequest) {
        this.rq = new XMLHttpRequest();
        if (this.rq.overrideMimeType)
        this.rq.overrideMimeType("text/xml"); 
    } else
        this.rq = new ActiveXObject("Microsoft.XMLHTTP");

    try {
        this.rq.onreadystatechange = connectionEvent;
        this.rq.open("GET", this.source, true);
        this.rq.send(null);
        this.state = 1;
    } catch (err) {
        // some error handler here
    }

}

function connectionEvent() {
    alert("i'm here");
    alert("this doesnt work: " + this.someOtherProperty);
}
Run Code Online (Sandbox Code Playgroud)

} // 我的课

所以它只不过是将XMLHttpRequest对象作为我的类的成员而不是全局定义,并以传统方式调用它.但是,在我的connectionEvent回调函数中,"this"的含义丢失了,即使函数本身是在myClass中的作用域.我还确保我从myClass实例化的对象保持足够长的时间(在脚本中声明为全局).

在我看到的所有使用javascript类的例子中,"this"仍在内部函数中可用.对我来说,它不是,即使我把我的函数带到外面并使它成为myClass.prototype.connectionEvent.我究竟做错了什么?谢谢.

javascript properties class xmlhttprequest onreadystatechange

3
推荐指数
1
解决办法
2784
查看次数