Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 229
decahub Avatar asked Sep 07 '25 02:09

decahub


2 Answers

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));
like image 178
optimistanoop Avatar answered Sep 08 '25 14:09

optimistanoop


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');
})();
like image 33
Aurélien Gasser Avatar answered Sep 08 '25 14:09

Aurélien Gasser