Underscore bind vs jQuery.proxy vs Native bind

半世苍凉 提交于 2019-12-07 03:37:25

问题


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?


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/18848343/underscore-bind-vs-jquery-proxy-vs-native-bind

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!