Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

While in most cases you can do that, they are not exactly equivalent. For example, you might be passing the callback to a function that attaches members to it.

But usually you see wrapping done in order to bind methods, like

  f = function(data) { return obj.doSomething(data);}
If you replaced that with

  f = obj.doSomething;
you'd likely have broken code.


A native method for binding methods has existed for a long time and is called just that:

    f = obj.doSomething.bind(obj);
    
Wrapping functions like in the example is different and is very common among cargo cultists


>A native method for binding methods has existed for a long time and is called just that:

Well, bind is a relatively recent addition. It wasn't added to IE until IE9, and it wasn't added to Safari until March 2012. In any case, I think that

  f = (data) -> obj.doSomething data
is far more readable than

  f = obj.doSomething.bind obj
Edit: it's also worth mentioning that in Chrome and FireFox, at least, the latter version of f is an order of magnitude slower than the former (http://jsperf.com/native-vs-non-native-bind)

But yes, wrapping functions is usually (but not always) silly.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: