Javascript OOP - 在异步回调中丢失了这个

yet*_*ety 7 javascript oop prototype callback this

我有问题仍然困扰我js oop - 我确定我做得不好,但我不能得到如何正确做到这一点.

例如,我有这个代码

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.');
      }
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是我无法从"request.onloadend"函数的上下文访问函数setToken - 这可能是因为我丢失了对"this"的引用.

这是什么问题的解决方案?我可以以某种方式将"this"var传递给此函数的上下文吗?

谢谢!

Jon*_*Jon 5

有几种方法可以做到这一点.最直接的是简单地保存所需值的副本:

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.');
      }
    }
}
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用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);
Run Code Online (Sandbox Code Playgroud)

第二种方法是"更干净",但它有浏览器兼容性问题(IE <9不支持它).