SOURCE

class PubSub {
    constructor(){
        this.subscribers = {}
    }
    //订阅
    subscribe(type, fn){
        console.log(Object.prototype.hasOwnProperty.call(this.subscribers,type),1111)
        if(!Object.prototype.hasOwnProperty.call(this.subscribers,type)){
            this.subscribers[type] = []
        }
        this.subscribers[type].push(fn);
    }
    //取消订阅
    unsubscribe(type, fn){
        let listeners = this.subscribers[type];
        if(!listeners || !listeners.length) return
        this.subscribers[type] = listeners.filter(v => v !== fn);
    }
    //发布
    publish(type,...args){
        let listeners = this.subscribers[type]; //获取订阅传入的方法
        if(!listeners || !listeners.length) return
        listeners.forEach(fn => fn(...args));//循环并调用函数
    }
}

let ob = new PubSub()
ob.subscribe('add', (val) => {
    console.log(val,222)
});

ob.unsubscribe('add', (val) => {
    console.log(val,555)
});

ob.publish('add',6)
console 命令行工具 X clear

                    
>
console