Reputation: 14740
I'm new to Javascript. This code mostly works but something weird happens. When I call .send()
it fires off the async request and returns normally but the problem is the this
context when calling the WebCall.prototype.__stateChangedCallback
method. In Chrome this
is the XMLHttpRequest object while I'd have thought that it would be the WebCall
object instead. Can anyone explain to me why this is?
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);
}
Upvotes: 1
Views: 1361
Reputation: 48793
What you have in WebCall.prototype.__stateChangedCallback
is just reference to anonymous function:
WebCall.prototype.__stateChangedCallback = function(readyState, status) {
//......................................^^^^ anonymous function
}
This line:
this.__callMethod.onreadystatechange = this.__stateChangedCallback;
means , that you have another reference to that same anonymous function. This anonymous function is not part of your prototype object.You just have reference on it in your prototype object.
Workaround would be this:
var that = this;
this.__callMethod.onreadystatechange = function(readyState, status){
//Calling anonymous function with 'this' context
WebCall.prototype.__stateChangedCallback.apply( that, arguments );
}
Upvotes: 1