Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct method for calling a callback function with "this"

Is this context valid for calling a callback function with the correct "this" context?

data.on('load', doSomething.call(this));

Or would it be better to use an additional arrow function (yes, I'm using babel to compile.

data.on('load', () => {
  doSomething.call(this);
});

Both seem to have the same result in Chrome but haven't checked other browsers. Is there a best practice or is one way better supported than another?

like image 428
ssylviageo Avatar asked Aug 05 '26 13:08

ssylviageo


1 Answers

The following will call doSomething immediately, and assign the returned value as the event listener:

data.on('load', doSomething.call(this));

You probably want bind instead:

data.on('load', doSomething.bind(this));

Your arrow function would work too.

like image 110
Oriol Avatar answered Aug 07 '26 04:08

Oriol