class Event { constructor() { //保存事件列表 this.eventList = []; } on(key,fn){ if ( !this.eventList[ key ] ){ this.eventList[ key ] = []; } this.eventList[ key ].push( fn ); } trigger(){ var key = Array.prototype.shift.call( arguments ), fns = this.eventList[ key ]; if ( !fns || fns.length === 0 ){ return false; } for( var i = 0, fn; fn = fns[ i++ ]; ){ fn.apply( this, arguments ); } } } //继承 class Test extends Event { constructor() { super(); this.init(); } init(){ window.setTimeout(()=>{ this.trigger(‘test‘,‘word:123‘,‘key:test‘); },3000); } } let t = new Test(); t.on(‘test‘,(word,key)=>{ alert(word); alert(key); }); //重复注册 t.on(‘test‘,(word,key)=>{ alert(key); alert(word); });
时间: 2024-10-27 12:13:56