I have problem which still bothers me on js oop - I'm sure I'm doing it bad, but I cant get how to do it right.
For example, I have this code
Auth.prototype.auth = function () {
var request = new XMLHttpRequest();
request.open('GET', this.getAuthServerURL() + '/token', true);
request.send();
request.onloadend = function () {
var response = JSON.parse(request.responseText);
console.log(response);
if(response.result == 'found') {
var token = response.token;
this.setToken(token);
this.isSigned = true;
} else {
console.log('Not logged yet.');
}
}
}
The problem is that I cant access to function setToken from context of "request.onloadend" function - its probably because I lost reference to "this".
Whats a solution of this problem? Can I somehow pass the "this" var to context of this function?
Thanks!
You can just capture a reference to it in the outer scope, I've used the identifier
self
, however please feel free to give the name a more semantic meaning:.bind
the function:There are a couple of ways to do this. The most direct is to simply save a copy of the value you need:
Another way is to use
bind
:The second approach is "cleaner", but it has browser compatibility issues (IE < 9 does not support it).
Capture
this
before the callback:You are quite right: the callback is called with the
XMLHTTPRequest
object as the context (i.e. the value ofthis
). You need to give your instance another name, so that you can access it within the scope of the callback:See this answer to another question for more explanation of why this is necessary. I have used
authInstance
rather thanself
, because I think it's generally good to use descriptive variable names; you'll never have to work out whatauthInstance
means, whereasself
might be ambiguous when someone in the future (possibly you!) reads the code.Another option is to use
bind
, but that is probably more complicated than necessary here.Save
this
in a local var outside the callback.