function Wechat(){ this.state = []; // 订阅 this.subscribe = function(obj){ this.state.push(obj) }; // 发布 this.publish = function(){ this.state.forEach(function(v){ v.natice(); }) }; // 取消订阅 this.unsubcribe = function(obj){ this.state.forEach((items,index)=>{ if(items === obj){ this.state.splice(index,1) } }) }; } var zhangsan = { 'name':'张三', natice:function(){ console.log(this.name+'收到了新闻') } } var lisi = { 'name':'李四', natice:function(){ console.log(this.name+'收到了新闻') } } var WechatPublish = new Wechat(); // 张三和李四订阅了 WechatPublish.subscribe(zhangsan) WechatPublish.subscribe(lisi) // 微信每隔2秒发布一个新闻给订阅的人 setInterval(function(){ WechatPublish.publish() console.log(WechatPublish.state) },2000) // 6秒后张三实在受不了了,一怒之下取消了订阅 setTimeout(function(){ WechatPublish.unsubcribe(zhangsan) console.log(WechatPublish.state) },6000)