我是Javascript的新手。这段代码大部分都有用,但有些奇怪。当我调用.send()
时,它会触发异步请求并正常返回,但问题是调用this
方法时WebCall.prototype.__stateChangedCallback
上下文。 Chrome中this
是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);
}
答案 0 :(得分: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 );
}