4 ms·
You can replace function(data) { return doSomething(data); } With doSomething Named functions are just as first-class as anyonymous ones...
by esailija 14y ago
You can replace
function(data) { return doSomething(data); }
With
doSomething
Named functions are just as first-class as anyonymous ones...
- insraq 14y agoWell, this is more of an example of the syntax. The lambda body might be quite complex.
- esailija 14y agoRight. But I have seen actual code do this plenty of times and there was no explanation in the article so I naturally assumed it was just like those cases where basics of functions are not understood.
- mistercow 14y agoWhile 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.
- esailija 14y agoA 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
- mistercow 14y ago>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 http://jsperf.com/native-vs-non-native-bind) But yes, wrapping functions is usually (but not always) silly.