While reading the docs for NodeJS at https://nodejs.org/api/events.html, I am a bit confused about this area of handling this in event listeners:
“It is possible to use ES6 Arrow Functions as listeners, however, when doing so, the this keyword will no longer reference the EventEmitter instance:”
const myEmitter = new MyEmitter();
myEmitter.on('event', (a, b) => {
console.log(a, b, this);
// Prints: a b {}
});
myEmitter.emit('event', 'a', 'b');
The object that this represents is empty. What does this reference in the arrow function, please?
Until arrow functions, every new function defined its own this value. This proved to be annoying with an object-oriented style of programming.
An arrow function does not create its own this context, so this has its original meaning from the enclosing context. Thus, the following code works as expected:
function Person(){
this.age = 0;
setInterval(() => {
this.age++; // |this| properly refers to the person object
}, 1000);
}
var p = new Person();
For more details check here and here too.
You can bind this to arrow functions, Try binding this by-
myEmitter.on('event', (a, b) => {
console.log(a, b, this);
// Prints: a b {}
}.bind(this));
As shanks noted in comments, this in the arrow function represents the context of the scope which encloses the arrow function.
Here's an example:
const EventEmitter = require('events')
const myEmitter = new EventEmitter();
this.foo = "bar";
myEmitter.on('event', () => {
console.log(this); // { foo: "bar" }
});
(function() {
this.foo = "baz";
myEmitter.emit('event');
})();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With