这件事几乎工程: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);
}
} // MyClass的
所以它不是什么比XMLHttpRequest对象为我的类的成员多,全局定义,并以传统方式调用它。然而,在我的connectionEvent回调函数中,“this”的含义会丢失,即使函数本身在myClass中有作用域。我还确保从myClass实例化的对象保持足够长的活动时间(在脚本中声明为全局对象)。
在我看到的所有使用javascript类的示例中,“this”在内部函数中仍然可用。对我来说,这不是,即使我把我的函数放在外面,并将其设置为myClass.prototype.connectionEvent。我究竟做错了什么?谢谢。
使用jQuery伟大的Ajax。 – sundowatch 2010-05-14 18:07:22
欢迎在Stackoverflow :)而是使用4个空格而不是每个缩进的选项卡。然后,当你在这里复制代码时,你必须用另外4个空格缩进*完整*片段。你可以通过选择一块,然后按消息编辑器工具栏中的'010101'按钮或'Ctrl + K'键来完成。 – BalusC 2010-05-14 18:10:30