Correct method to call a callback function with & ldquo; This & quot;

微信扫一扫,分享到朋友圈

Correct method to call a callback function with & ldquo; This & quot;

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?

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.

微信扫一扫,分享到朋友圈

Correct method to call a callback function with & ldquo; This & quot;

5 ways tennis and investingincrease my productivity as a software engineer

上一篇

Scala class that manages enumerations generically

下一篇

你也可能喜欢

Correct method to call a callback function with & ldquo; This & quot;

长按储存图像,分享给朋友