3
I’m doing my Javascript studies, and I’m doing some pretty simple to consume an API, but I got an error. Before I comment on it, I’ll show you my code:
View js.
var model = new Model();
var response = null;
model.setUrl("https://jsonplaceholder.typicode.com/users");
model.openXhr("GET");
Model js.
var Model = function() {
var _url = null;
var _xhr = new XMLHttpRequest();
var _message = {};
var _response = null;
this.setUrl = function (url) {
_url = url;
}
this.getUrl = function (url) {
return _url;
}
this.openXhr = function(method) {
_xhr.open(method, this.getUrl());
_xhr.onload = this.onLoadXhr;
_xhr.send();
}
this.onLoadXhr = function() {
if (_xhr.status === 200)
_message.status = "success";
else
_message.status = "failed";
var response = this.parseResponse(_xhr.responseText); // this.parseResponse is not a function
this.setResponse(response);
}
this.parseResponse = function(response) {
return JSON.parse(response);
}
this.setResponse = function(response) {
_response = response;
}
this.getResponse = function() {
return _response;
}
}
The problem
var response = this.parseResponse(_xhr.responseText); // this.parseResponse is not a function
See that comes to this part it gives this error when calling the function. Printing the this
I found that he is not from the context of the function, but from the _xhr
. Why? In another part of the code I do a similar operation and it doesn’t happen _xhr.onload = this.onLoadXhr;
. Here I referred to onLOadXhr
within the openXhr
.
So whenever you pass a function as a reference it will not come with associated context ?
– Allan Ramos
@Allanramos depends, in which case the function is called as
XMLHttpRequest
and hence the context change.– Sergio
Because it is associated with the XHR object. If I didn’t have this object, how would it look ?
– Allan Ramos
@Allanramos added an example to the answer
– Sergio