Javascript OOP - 在异步回调中丢失了 [英] Javascript OOP - lost this in asynchronous callback
问题描述
我有问题,仍然困扰我在js oop - 我相信我做错了,但我不能得到如何做到正确。
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.
例如,我有这个代码
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.');
}
}
}
问题是,从request.onloadend函数的上下文访问函数setToken - 它可能是因为我失去了对this的引用。
The problem is that I cant access to function setToken from context of "request.onloadend" function - its probably because I lost reference to "this".
这个问题的解决方案是什么?我可以以某种方式将thisvar传递给此函数的上下文。
Whats a solution of this problem? Can I somehow pass the "this" var to context of this function?
谢谢!
推荐答案
有几种方法可以做到这一点。最直接的是简单地保存您需要的值的副本:
There are a couple of ways to do this. The most direct is to simply save a copy of the value you need:
Auth.prototype.auth = function () {
var request = new XMLHttpRequest();
var self = this; // save "this" value
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;
self.setToken(token); // use saved "this" value
self.isSigned = true;
} else {
console.log('Not logged yet.');
}
}
}
另一种方法是使用< a href =https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/bind =nofollow> bind
:
Another way is to use bind
:
request.onloadend = (function () {
var response = JSON.parse(request.responseText);
console.log(response);
if(response.result == 'found') {
var token = response.token;
this.setToken(token); // use saved "this" value
this.isSigned = true;
} else {
console.log('Not logged yet.');
}
}).bind(this);
第二种方法是更干净,但它有浏览器兼容性问题(IE< 9不支持它)。
The second approach is "cleaner", but it has browser compatibility issues (IE < 9 does not support it).
这篇关于Javascript OOP - 在异步回调中丢失了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!