Javascript Usages Of Bind Vs Curry*?
Solution 1:
bind
forces you to attach a context to the function, while by using curry
, you can delay the specification of function context until invoking the curried function, useful in many cases.
consider the following example (not the perfect one, just to illustrate the idea):
functionQuery(sessionKey, dataBuilder) {
this.sessionKey = sessionKey;
this.url = "http://www.example.com/search";
this.dataBuilder = dataBuilder
this.search = function (term) {
$.ajax({
type: "POST",
url: this.url,
data: this.dataBuilder(term);
})
}
}
functiondataBuilder(entity, query) {
var payload = JSON.stringify({
'entity': entity,
'searchTerm': query
'session': this.sessionKey// will be always undefined if bind(undefined,...) is used
});
return payload
}
var bindEx= dataBuilder.bind(undefined, "username");
var curryEx= dataBuilder.curry("username");
var usernameQuery = newQuery("id1234",bindEx); // won't work, this.sessionKey will be undefined
usernameQuery = newQuery("id1234",curryEx); // will work, this.sessionKey will be id1234 in the DataBuilder
Solution 2:
There is a difference in intention.
Currying is to reduce the number of arguments, usually to avoid calling a function a lot with the same initial arguments. For example:
var celsiusToKelvin = add.curry(273.15);
bind() is to make sure that a function is attached to an object. It also happens to offer a currying facility, so yes you can use bind() to curry(), but if you want to curry, curry() has fewer arguments and shows your intention.
Solution 3:
I'd think it has something to do with compatibility with older browsers as bind is only available since ECMAScript 5.
See this for a list of .bind()
support: http://kangax.github.io/es5-compat-table/
Also from what I've heard, most people still use curry because it looks cleaner as it doesn't need that extra undefined
in the arguments.
Post a Comment for "Javascript Usages Of Bind Vs Curry*?"