Last Updated: February 25, 2016
·
631
· kelion

Simplify your code by using function.bind

Function.prototype.bind — is great function that can help you clear you code. I see few common examples, when it is useful. First is functions like moveUp/moveDown, increaseValue/decreaseValue etc. Abstract example:

$arrowUp.on('click', function(){
    currentPosition += 1;
    applyChanges();
});

$arrowDown.on('click', function(){
    currentPosition -= 1;
    applyChanges();
});

Lets simplify this code by use .bind:

function move(diff) {
    currentPosition += diff;
    applyChanges();
};
$arrowUp.on('click', move.bind(null, 1));
$arrowDown.on('click', move.bind(null, -1));

Looks better, right?

Second example is calling function with parameters in callbacks. For example, setTimeout/setInterval:

$(window).load(function(){
    setTimeout(loadSomething, 5000);
});

We can use bind and change it to one line:

$(window).load(setTimeout.bind(null, loadSomething, 500));

Another example from angular.js. We wanted to store few user preferences in localStorage and code was like:

$scope.$watch('language', function(value){
    $localStorage.set('language', value);
});

$scope.$watch('timezone', function(value){
    $localStorage.set('timezone', value);    
});
...

And we refactored it:

$scope.$watch('language', $localStorage.set.bind(null, 'language'));
$scope.$watch('timezone', $localStorage.set.bind(null, 'timezone'));
...

It is easier to read, looking better, and make your code smaller.

And dont forget to add polyfill for old browser to use this function!