代码如下:
class EventEmitter {
constructor() {
this.events = this.events || new Map();
}
addListener(type, fn) {
if (!this.events.has(type)) {
this.events.set(type, fn);
}
}
emit(type) {
const fn = this.events.get(type);
fn.apply(this, [...arguments].slice(1));
}
}
const eventEmitter = new EventEmitter();
eventEmitter.addListener('add', function (a, b) {
console.log(a + b);
});
eventEmitter.emit('add', 23, 22);