function Observer(){ this.observers=new Set() } Observer.prototype.subscribe=function(fn){ this.observers.add(fn) let self = this return function unsubscribe(){ self.observers.delete(fn) } } Observer.prototype.dispatch=function(){ this.observers.forEach(ob=>ob()) } const ob=new Observer() const sb1=ob.subscribe(function(){alert(1)}) const sb2=ob.subscribe(function(){alert(2)}) ob.dispatch() sb2() ob.dispatch()