Reputation:
I noticed there is _.bind
and _.bindAll
in Underscore. I was wondering when do you use one over the other? What if you have multiple this
that you need to bind, which one would you use?
Upvotes: 1
Views: 694
Reputation: 413737
Well they do similar but quite different things. The _.bind()
function is for binding a single function to an object, while _.bindAll()
is about binding some or all of the function-valued properties of an object to the object.
Thus _.bind()
is useful when you've got any situation that requires a function be invoked with a fixed receiver, and _.bindAll()
is useful when you're working with more "objecty" code. That is the case when you've got objects with properties that are functions, and these functions expect (require) that they be invoked with the object as the receiver so that they can access other functions.
The examples in the Underscore documentation explain further.
Note that modern JavaScript runtime environments have a .bind()
method on the Function prototype, which (seems to me) should be preferred over _.bind()
.
edit — As to your questions about having to create bound functions for multiple objects, the answer is that neither of _.bind()
and _.bindAll()
addresses that. You simply have to iterate somehow and collect the bound functions in some appropriate way.
Upvotes: 3