Wednesday, September 10, 2014

Stop using thiz, that, and self...

Quite often, I come across code that needs to keep track of "this" while still calling inner functions or callbacks. In each case, "this" has been reassigned to some other variable to keep a handle on it. See below:

userObj.getExtraData = function (cb) {
  var that = this;
  getAsyncData(function (data) {
    that.extraData = data;
    cb();
  });
};

userObj.getExtraData(function () {
  console.log(userObj.extraData);
});


You can get rid of those pesky variables (thiz, that, self, _this, whatever) by just using Function.prototype.bind like so:

userObj.getExtraData = function (cb) {
  getAsyncData(function (data) {
    this.extraData = data;
    cb();
  }.bind(this));
};

userObj.getExtraData(function () {
  console.log(userObj.extraData);
});


Huzzah!! We've got "this" back!

Edit:

The new ES6 syntax makes this a lot easier with big arrow syntax. It gives you a shorthand for writing functions while auto-binding your context. This:

(data) => {
   // do stuff
}

Is equivalent to this:

function (data) {
 // do stuff
}.bind(this);

Hence, the example turns into:

userObj.getExtraData = function (cb) { 
  getAsyncData((data) => { 
    this.extraData = data; 
    cb(); 
  });
}; 

userObj.getExtraData(function () { 
  console.log(userObj.extraData); 
});

No comments:

Post a Comment