The wonders of .bind()

Here’s a quick cool tip to improve code smoothness.

How many times have you

var self = this;

or

var _this = this;

and all these variants? I always hated typing this - pun not intended. Usually it is required to do it when the scope for this is overridden.

E.g.:

var array = [1,2,3,4],  
  self  = this;
this.another_function = function(args){/*…*/};  
array.forEach(function(element){  
  // verbose iterating code
    self.another_function(element);
});

How to overcome this little issue? Through Function.prototype.bind! Applying to the piece of code above:

var array = [1,2,3,4];  
this.another_function = function(args){/*…*/};  
array.forEach(function(element){  
  // verbose iterating code
    this.another_function(element);
}.bind(this));

One recurrent use case is setTimeout:

this.value = 1;  
setTimeout(function(){ this.value++; }.bind(this), 1000);

Another recurrent use case is on object scoping:

var obj = {  
  value: 1,
    getValue: function(){ return this.value; }
};

this.value = 2;  
obj.getValue(); // Evals 1  
obj.getValue.bind(this)(); // Evals 2

This is vanilla Javascript, no libs required. Read more about it here.