kofifus kofifus - 2 years ago 88
Javascript Question

ES6 arrow function with no parameters


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());

is any of these options preferable ?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download