Skip to content

Instantly share code, notes, and snippets.

@seidtgeist
Last active December 18, 2015 12:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save seidtgeist/5783174 to your computer and use it in GitHub Desktop.
Save seidtgeist/5783174 to your computer and use it in GitHub Desktop.
// 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);
};
}
@raganwald
Copy link

Here's why .bind is appropriate:

o = { name: 'me', greeting: function (who) { return "Hello, " + who + ", my name is " + this.name; } }
  //=> Object
o.greeting('you')
  //=> "Hello, you, my name is me"
f = o.greeting
  //=> function (who) { return "Hello, " + who + ", my name is " + this.name; }
f('you')
  //=> "Hello, you, my name is "
b = o['greeting'].bind(o)
  //=> function () {
         [native code]
       }
b('you')
  //=> "Hello, you, my name is me"
b.length
  //=> 1

With v2, the bound function's length is thrown away. try currying a bound function and you'll see why this matters :-)

@seidtgeist
Copy link
Author

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?

@raganwald
Copy link

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