Thursday, May 15, 2014

Using this or that in Javascript, or maybe bind?

When accessing the current context from within an anonymous function in Javascript one usually assigns the current scope to a variable and it gets closed over:

For example:
_ = require('underscore');

var y = [ 'this', 'that', 'whatever' ];
var test = function () {
  var that = this;
  this.x = 'use ';
  _.each(y, function(item) {
    console.log(that.x + item);
  });
}

test();
We had a little debate about whether we should use 'self' or 'that' to pass in the context. But maybe we're all wrong, because there's a function called bind in underscore which handles all that for us...
_ = require('underscore');

var y = [ 'this', 'that', 'whatever' ];
var test = function () {
  this.x = 'use ';
  _.each(y, _.bind(function(item) {
    console.log(this.x + item);
  }, this));
}

test();

No comments: