私はJavascriptが初めてです。このコードはほとんど機能しますが、奇妙なことが起こります。私が呼び出す.send()
と、非同期リクエストが発生し、正常に戻りますが、問題はメソッドthis
を呼び出すときのコンテキストです。WebCall.prototype.__stateChangedCallback
Chromeでは XMLHttpRequest オブジェクトですが、代わりthis
にオブジェクトになると思っていました。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);
}