BruceM BruceM - 3 years ago 258
Javascript Question

How to use arrow function instead of 'bind' in a helper function

I have a class, which imports a helper function

import {foo} from '../helper/foo';
foo(someArg, this.retFunc.bind(this));

Which works fine - I call the helper function 'foo', pass it an argument 'someArg' and it calls the retFunc with the proper context for 'this'.

Hoew would I replace the above with an arrow function? When I do the following, retFunc never gets called:

foo(someArg, () => this.retFunc);

Answer Source

There are two issues with

foo(someArg, () => this.retFunc)

First, the callback function (() => this.retFunc) does not call the function, and will only return a function when the callback is called, which is probably not helpful in you example.


foo(someArg, () => this.retFunc())

has another issue, which is that any parameters passed to the callback function will be ignored, and won't be passed to this.retFunc(). This can be a good thing, or a bad thing, depending on what you expect retFunc to need for parameters.

As you're after a substitute for .bind(this) then the appropriate replacement would be to use rest parameters to pass any input to your function:

foo(someArg, (...args) => this.retFunc(...args))

All that said, you're not saving anything by attempting to replace bind in this particular example:

foo(someArg, this.retFunc.bind(this))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download