Javascript OOP - lost this in asynchronous callbac

2019-02-21 21:54发布

问题:

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!

回答1:

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



回答2:

.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
}


回答3:

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


回答4:

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


回答5:

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


回答6:

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.