The question revolves around how the this
keyword behaves in javascriptJavaScript. this
behaves differently as below,
- The value of
this
is usually determined by a function execution context. - In the global scope,
this
refers to the global object (thewindow
object). - If strict mode is enabled for any function then the value of
this
will beundefined
as in strict mode, global object refers toundefined
in place of thewindow
object. - The object that is standing before the dot is what thisthe
this
keyword will be bound to. - We can set the value of this explicitly with
call()
,bind()
, andapply()
- When the
new
keyword is used (a constructor), this is bound to the new object being created. - Arrow Functionsfunctions don’t bind
this
— instead,this
is bound lexically (i.e., based on the original context)
As most of the answers suggest, we can use Arrowthe arrow function or bind()
Method or Self var. I would quote a point about lambdas (Arrowarrow function) from Google JavaScript Style Guide
Prefer using arrow functions over f.bind(this), and especially over goog.bind(f, this). Avoid writing const self = this. Arrow functions are particularly useful for callbacks, which sometimes pass unexpectedly additional arguments.
Google clearly recommends using lambdas rather than bind or const self = this
So the best solution would be to use lambdas as below,
function MyConstructor(data, transport) {
this.data = data;
transport.on('data', () => {
alert(this.data);
});
}
References: