6

I have some context issues in callback. I googled and found few option:

  1. Native bind - not supported by old browsers
  2. JQuery proxy
  3. underscore bind

I'll definitely use native bind if I don't have to support old browsers. Is there any significant difference between these one should be aware of?

Could these be used as an alternate to call/apply?

RuntimeException
  • 1,135
  • 2
  • 11
  • 25

2 Answers2

18

AFAIK, There is a slight difference between bind and proxy, which can matter a lot if you are using jQuery. Function.prototype.bind always returns a new function pointer. jQuery.proxy only returns a new function if a proxy of the same args has not already been created. Not that you would want to do it like this, but:

$(elm).on('click', doStuff.bind(thing)); //adds event handler
$(elm).off('click', doStuff.bind(thing)); //does not remove event handler as 2nd call of doStuff.bind(thing) always returns a new/different function

$(elm).on('click', $.proxy(doStuff, thing)); //adds handler
$(elm).off('click', $.proxy(doStuff, thing));//DOES remove handler, as a second call to $.proxy(doStuff, thing) is smart enough to know about similar use-cases

//Likewise, if you just passed 'thing.doStuff()' into the $.off() method, it would also work
Graza
  • 5,010
  • 6
  • 32
  • 37
  • 2
    Confirmed with this [jsFiddle test](http://jsfiddle.net/plantface/ov39js45/). Turning .on() both event handlers and then turning them .off() again confirms the .bind() eventhandler still fires. – Benny Bottema Sep 05 '14 at 09:55
  • ugh this whole "function pointer" situation always makes me super annoyed at whoever designed the event system. Thanks! – nightpool Jan 03 '16 at 20:23
2

The call and apply methods invoke a function. The bind method returns a function object that can be used a reference (for use in callbacks, for instance). Therefore, bind and call/apply don't generally have the same use cases.

That being said, MDN has a polyfill for the bind method of a function object right on the method specification page (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) in case you need to use it in browsers where it's not supported (basically IE < 8...so in my book IE8 is the only browser that I support that doesn't have it natively).

Lastly, don't ever consider including an entire library just because you need one of its functions.

temporary_user_name
  • 35,956
  • 47
  • 141
  • 220
Adam Jenkins
  • 51,445
  • 11
  • 72
  • 100
  • So proxy and bind are exactly same? – RuntimeException Sep 17 '13 at 11:50
  • You can read that in the docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind vs http://api.jquery.com/jQuery.proxy/ - but the purpose of $.proxy() is the same as the purpose of bind() - to change the context (i.e. the 'this' reference) of a given function. – Adam Jenkins Sep 17 '13 at 13:06