Javascript OOP - lost this in asynchronous callbac

2019-02-21 21:34发布

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!

6条回答
一纸荒年 Trace。
2楼-- · 2019-02-21 22:02

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:

var self = this;
request.onloadend = function () {
  ...
  self.setToken(token);
  ...
};
查看更多
一纸荒年 Trace。
3楼-- · 2019-02-21 22:03

.bind the function:

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.');
      }
    }.bind(this); //<-- bound
}
查看更多
女痞
4楼-- · 2019-02-21 22:07

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.');
      }
    }
}

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);

The second approach is "cleaner", but it has browser compatibility issues (IE < 9 does not support it).

查看更多
来,给爷笑一个
5楼-- · 2019-02-21 22:14

Capture this before the callback:

Auth.prototype.auth = function () {
    var self = this;

    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;

        self.setToken(token);
        self.isSigned = true;
      } else {
        console.log('Not logged yet.');
      }
    }
}
查看更多
爱情/是我丢掉的垃圾
6楼-- · 2019-02-21 22:23

You are quite right: the callback is called with the XMLHTTPRequest object as the context (i.e. the value of this). You need to give your instance another name, so that you can access it within the scope of the callback:

Auth.prototype.auth = function () {
    var request = new XMLHttpRequest(),
        authInstance = this;

    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;

        authInstance.setToken(token);
        authInstance.isSigned = true;
      } else {
        console.log('Not logged yet.');
      }
    }
}

See this answer to another question for more explanation of why this is necessary. I have used authInstance rather than self, because I think it's generally good to use descriptive variable names; you'll never have to work out what authInstance means, whereas self 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.

查看更多
smile是对你的礼貌
7楼-- · 2019-02-21 22:25

Save this in a local var outside the callback.

Auth.prototype.auth = function () {
    var request = new XMLHttpRequest();
    var _this = this;

    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.');
      }
    }
}
查看更多
登录 后发表回答