CodePark/ questions / this in methods & callbacks
START PRACTICINGPRACTICE
Backend question · Object-oriented programming › this in methods & callbacks

What does this print in Node.js?

const { EventEmitter } = require("node:events");
class Counter {
  count = 0;
  handle() { this.count++; }
}
const c = new Counter();
const e = new EventEmitter();
e.on("tick", c.handle);
e.emit("tick");
e.emit("tick");
console.log(c.count, e.count);
0 NaN

It prints 0 NaN. Node calls a normal-function listener with this set to the emitter. So this.count++ runs on e, not on c. e.count starts as undefined, and undefined + 1 is NaN. c.count never changes.

"A
TypeError on the first emit" is tempting, because a detached method usually gets undefined as this. Here the emitter gives it a this, so the bug is silent. That is worse.