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".
这个问题的解决方案是什么?我可以以某种方式将这个"变量传递给这个函数的上下文吗?
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.');
}
}
}
另一种方法是使用 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屋!