代码实现
function Event(){
this.handles = {}
}
Event.prototype.on = function(evName, callback){
if(!this.handles[evName]){
this.handles[evName] = []
}
this.handles[evName].push(callback)
}
Event.prototype.emit = function(evName, ...args){
const handle = this.handles[evName]
if(handle){
for(let i=0,len=handle.length;i<len;i++){
handle[i](...args)
}
}
}
let event = new Event()
event.on('step', (...args)=>{console.log(...args)})
event.emit('step', 10, 'huahua')
event.emit('step', 20, 'xiaoming')
function Child(){}
Child.prototype = new Event()
let child = new Child()
child.on('step', (...args)=>{console.log(...args)})
child.emit('step', 30, '二狗子')
child.emit('step', 90, '法外狂徒张三')