const EventEmitter = require('events').EventEmitter;
const Counter = function (init) {
this.increment = function () {
init++;
this.emit('incremented', init);
}
}
Counter.prototype = new EventEmitter();
const counter = new Counter(10);
const callback = function (count) {
console.log(count);
}
counter.addListener('incremented', callback);
counter.increment(); // 11
counter.increment(); // 12
In the code snippet above, when this
is used in this.increment
, it refers to the counter object. However, what does the this
refer to in this.emit
? Does it point to the increment object or the counter object? Additionally, how is the emit function executed?