自定義全局事件

原理markdown

建立包含事件type及其回調函數列表callbackFn list、監聽函數on、觸發函數emit,而後全局共享該對象便可app

實現函數

function commonEvent(){
    this.handlers = {};
    this.on = function(type,callback){
        this.handlers[type] = this.handlers[type]||[];
        this.handlers[type].push(callback);
    }
    this.emit = function(type,...args){
        if(this.handlers[type]){
            this.handlers[type].forEach(f=>f.apply(null,args));
        }
    }
}
複製代碼

擴展ui

利用函數原型及屬性描述對象來凍結原生函數,防止篡改this

相關文章
相關標籤/搜索