1

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

1 に答える 1

2

あなたが持っているのWebCall.prototype.__stateChangedCallbackは、無名関数への参照だけです:

WebCall.prototype.__stateChangedCallback = function(readyState, status) {
   //......................................^^^^ anonymous function
}

この行:

this.__callMethod.onreadystatechange = this.__stateChangedCallback;

は、同じ無名関数への別の参照があることを意味します。この無名関数は、プロトタイプ オブジェクトの一部ではありません。プロトタイプ オブジェクトで参照されているだけです。

回避策は次のとおりです。

var that = this;
this.__callMethod.onreadystatechange = function(readyState, status){
    //Calling anonymous function with 'this' context
    WebCall.prototype.__stateChangedCallback.apply( that, arguments );
}
于 2012-05-20T06:02:11.457 に答える