1

If I want to print the event object in Node.js using a callback function, this works:

Example 1

const events = require( 'events' );

var eventEmitter = new events.EventEmitter();

eventEmitter.on( 'customEventNameGoesHere', function() {
    console.log( this );
} );

eventEmitter.emit( 'customEventNameGoesHere' );

/* Sample output:
EventEmitter {
  _events:
   [Object: null prototype] { customEventNameGoesHere: [Function] },
  _eventsCount: 1,
  _maxListeners: undefined }
*/

However, if I try using an arrow function, it doesn't work:

Example 2

const events = require( 'events' );

var eventEmitter = new events.EventEmitter();

eventEmitter.on( 'customEventNameGoesHere', () => { console.log( this ); } );

eventEmitter.emit( 'customEventNameGoesHere' );

/* Sample output:
{}
*/

What do I need to change in Example 2 to print the value of the event object using the keyword "this"? Trying to access the local value of "this" instead of the parent value. How?

GTS Joe
  • 3,612
  • 12
  • 52
  • 94

0 Answers0