我是 Javascript 的新手。这段代码大部分都有效,但发生了一些奇怪的事情。当我调用.send()
它时,它会触发异步请求并正常返回,但问题是this
调用该WebCall.prototype.__stateChangedCallback
方法时的上下文。在 Chromethis
中是 XMLHttpRequest 对象,而我原以为它会是WebCall
对象。谁能向我解释这是为什么?
function log (message) {
if(typeof console == "object") {
console.log(message);
}
}
function WebCall () {
var __callMethod;
this.__callMethod = this.createXmlHttpRequest();
}
WebCall.prototype.createXmlHttpRequest = function () {
if(window.XMLHttpRequest) {
return new XMLHttpRequest();
} else {
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
WebCall.prototype.beginGet = function(url) {
this.__callMethod.open("GET", url, true);
this.__callMethod.onreadystatechange = this.__stateChangedCallback;
this.__callMethod.send();
}
WebCall.prototype.__stateChangedCallback = function(readyState, status) {
// this points to the XMLHttpRequest rather than the WebCall object WHY??!
var request = this.__callMethod;
if(request.readyState == 4) {
if (request.status == 200) {
this.onRequestCompleted(request);
} else {
this.onRequestFailed(status, request);
}
}
}
WebCall.prototype.onRequestCompleted = function (request) {
}
WebCall.prototype.onRequestFailed = function(status, request) {
log("Request failed status= " + status);
}