Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 arrow function with no parameters [duplicate]

Tags:

considering

function f() { ... }

and another function dosomething expecting a function like f

function dosomething(callback) { ...; callback() } 

that expects f (an example of dosomething can be setTimeout)

calling dosomething and passing f, is there a difference between:

dosomething(f);

and

dosomething(() => f());

is any of these options preferable ?

like image 646
kofifus Avatar asked Apr 19 '16 00:04

kofifus


1 Answers

That the wrapping function (second example) is an arrow function or not does not change a thing here.

However, this wrapping function can be useful to forbid arguments transfer: in the first case, if callback is called with an argument, it will be given to f. Not in the the second case. An alternative could be to restrict the number of transmitted arguments: dosomething((a, b) => f(a, b));.

It can also be used to protect against this injection: in the first case, doSomething can bind f to change its this (callback.bind(whatever)). With a wrapping function (arrow or not), it won't have any effect and f will keep his this (the global context) whatever doSomething does.

like image 63
Quentin Roy Avatar answered Oct 11 '22 01:10

Quentin Roy