实现原生on off tigger once 方法
最近听到别人面试,很多次考到了这种题目,今天整理了一下笔记,看到就整理出来大家一起学习,有什么不对的请指教。
class Event {
constructor() {
this.handlers = {}
}
on(type, handler, once=false){
if(!this.handlers[type]){
this.handlers[type] = []
}
if(!this.handlers[type].includes(handler)){
this.handlers[type].push(handler)
handler.once = once
}
}
tigger(type,eventData={},point=this){
if(this.handlers[type]){
this.handlers[type].forEach(f => {
f.call(point, eventData)
if(f.once){
this.off(type,f)
}
})
}
}
off(type, handler){
if(this.handlers[type]){
if(handler === undefined){
this.handlers[type] = []
}else{
this.handlers[type] = this.handlers[type].filter(
f => f != handler
)
}
}
}
once(type, handler){
this.on(type, handler, true)
}
} 
查看7道真题和解析