Saturday, 6 May 2017

NodeJS: Passing arguments and this to listeners

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?



via decahub

No comments:

Post a Comment