这东西几乎可以工作:
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);
}
} // 我的课
所以它只不过是让 XMLHttpRequest 对象作为我的类的成员,而不是全局定义,并以传统方式调用它。但是,在我的 connectionEvent 回调函数中,“this”的含义丢失了,即使该函数本身在 myClass 中也是如此。我还确保我从 myClass 实例化的对象保持活动的时间足够长(在脚本中声明为全局)。
在我看到的所有使用 javascript 类的示例中,“this”在内部函数中仍然可用。对我来说,它不是,即使我把我的函数带到外面并将它变成一个 myClass.prototype.connectionEvent。我究竟做错了什么?谢谢你。