自定义全局事件

原理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

相关文章
相关标签/搜索