function Subscriber() { this.subs = []; } Subscriber.prototype.subscribe = function (sub) { console.log("add sub"); if(this.subs.indexOf(sub) < 0){ this.subs.push(sub); } }; Subscriber.prototype.unsubscribe = function(sub){ console.log("unsubscribe"); for(var i=0; i<this.subs.length; i++){ if(sub === this.subs[i]){ this.subs.splice(i, 1); } } }; Subscriber.prototype.publish = function () { console.log("publish"); this.subs.forEach(function (cb) { cb(); }); }; var subsriber = new Subscriber(); function func1() { console.log("func1"); } function func2() { console.log("func2"); } function func3() { console.log("func3"); } subsriber.subscribe(func1); subsriber.subscribe(func2); subsriber.subscribe(func2); subsriber.subscribe(func3); subsriber.unsubscribe(func2); subsriber.publish();
代码结构很清晰