阿里面试题为例
完成 EventEmitter 模块,它是一个类,它的实例具有以下几个方法:on、emit、off:
on(eventName, func):监听 eventName 事件,事件触发的时候调用 func 函数。
emit(eventName, arg1, arg2, arg3...):触发 eventName 事件,并且把参数 arg1, arg2, arg3... 传给事件处理函数。
off(eventName, func):停止监听某个事件。
class EventEmitter {
constructor() {
this.handlers = {}
}
on(eventName, func) {
let callbacks = eventName in this.handlers ? this.handlers[eventName] : []
callbacks.push(func)
this.handlers[eventName] = callbacks
}
emit(eventName, ...args) {
if (!eventName in this.handlers) return
const callbacks = this.handlers[eventName]
callbacks.map(cb => {
cb(...args)
})
}
off(eventName, func) {
if (!eventName in this.handlers) return
let callbacks = this.handlers[eventName]
let index = callbacks.indexOf(func)
callbacks.splice(index, 1)
}
}
const emitter = new EventEmitter()
const sayHi = (name) => console.log(`Hello ${name}`)
const sayHi2 = (name) => console.log(`Good night, ${name}`)
emitter.on('hi', sayHi)
emitter.on('hi', sayHi2)
emitter.emit('hi', 'ScriptOJ')
// => Hello ScriptOJ
// => Good night, ScriptOJ
emitter.off('hi', sayHi)
emitter.emit('hi', 'ScriptOJ')
// => Good night, ScriptOJ
const emitter2 = new EventEmitter()
emitter2.on('hi', (name, age) => {
console.log(`I am ${name}, and I am ${age} years old`)
})
emitter2.emit('hi', 'Jerry', 12)
// -------------------------------------------------------------------------------
class Person extends EventEmitter {
constructor(name) {
super()
this.name = name;
this.age = 1;
// this.on('growup', () => {
// console.log('ceshi' + this.name);
// })
// this.growup()
}
growup() {
setInterval(() => {
this.age++;
this.emit('growup');
}, 1000);
}
}
const p1 = new Person('xiao_liu');
const p2 = new Person('xiao_liu1');
p1.on('growup', () => {
console.log('长大一岁');
})
p2.on('growup', () => {
console.log('长大一岁');
})
p1.growup()
p2.growup()
网友评论