Function.prototype.bind and friends
I thought bind
was only used to attach a new this
to a function. Turns out I had it wrong all along. You can use it to partially apply functions.
I have been doing this in a different way.
Suppose you want a somewhat generic iterator function. This was the only way I knew how to make it happen.
function partiallyApplyMe(firstArg){
return function(secondArg){
console.log(firstArg+secondArg);
}
}
_.each(list,partiallyApplyMe('list:'));
_.each(obj,partiallyApplyMe('obj:'));
The alternative is to simply write the iterator function with the following function declaration: function iterator(firstArg,secondArg)
and then use it like so:
_.each(list,iterator.bind(undefined,'list:')); _.each(obj,iterator.bind(undefined,'obj:'));
//or if you like ES5:
list.forEach(iterator.bind(undefined,'list:'));
//not quite the same...but you get the picture
Object.prototype.keys(list).forEach(iterator.bind(undefined,'obj:'));
This is far simpler and I will be using this in all new code I write.