0

I happened to review the following code today

var triggerWindowResize = $.fn.resize.bind($($window));
var redraw = $timeout.bind(null, triggerWindowResize);

And I thought: that's not how I would do it; I would do it like that

var triggerWindowResize = () => $(window).resize();
var redraw = () => $timeout(triggerWindowResize);

I believe the => version is better mostly because it makes it clearer what the code is supposed to do. But of course, there may be other things I'm not taking into account here.

Ignoring the fact these functions could be called with a different number of arguments, which do you think is better? And should there be a coding style that says always use one or the other?

We do use both .bind and => in various parts of our code, so browser support etc. is not relevant here.

configurator
  • 40,828
  • 14
  • 81
  • 115
  • Did you mean `$(window)` instead of `$($window)`? – Andrew Li Feb 16 '17 at 22:00
  • `bind` will set the value of `this`. In the first version the user can refer to `$($window)` by `this`, but in the second it will relative to where it's defined (`this` is whatever object that line is in)! – ibrahim mahrir Feb 16 '17 at 22:00
  • Whichever you like better (if [the differences](http://stackoverflow.com/a/32539428/1048572) don't matter). And don't forget the arguments, they're important. – Bergi Feb 16 '17 at 22:10
  • "Better" requires some objective criteria for evaluation, which might be different for different contexts. E.g. *bind* is more widely supported and can be [*polyfilled*](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind#Polyfill), arrow functions can't (though they can be transpiled). Those features may be more or less important in your decision making, there is no definitive "best". – RobG Feb 16 '17 at 22:53

0 Answers0