Last active
December 18, 2015 12:29
-
-
Save seidtgeist/5783174 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Motivation: | |
// | |
// I see myself writing this quite often: | |
f(_.bind(obj.m, obj)) | |
// but I could write: | |
f(bound(obj, 'm')); | |
// @evilhackerdude v1 | |
function bound(object, fn) { | |
return _.bind(object[fn], object); | |
} | |
// @raganwald | |
function bound(object, fn) { | |
return object[fn].bind(object); | |
} | |
// @evilhackerdude v2 | |
function bound(object, fn) { | |
return function() { | |
object[fn].apply(object, arguments); | |
}; | |
} |
With v2, the bound function's length is thrown away.
Correct, a good reason to use native bind
.
We could however still use underscore's bind impl which delegates to Function.prototype.bind
:
c = _.bind(o['greeting'], o)
// => [Function]
> c('you')
// => 'Hello, you, my name is me'
> c.length
// => 1
- Gives us
length
- Works with JS runtimes that don't support native
bind
(notably, i think iOS < or <= 5 doesn't)
Of course, the funniest problems arise when code depends on length
(curry?) and it doesn't work consistently. Would be a reason to use native bind
and fail early?
I have some code that can force an arity in allong.es, I use it precisely because I wanted to make sure that everything interoperates with curry and partial application. We could look at whether to "improve" bind such that it preserves length even in older browsers.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's why
.bind
is appropriate:With v2, the bound function's length is thrown away. try currying a bound function and you'll see why this matters :-)