观察者模式顾名思义,有观察者 被观察者, 这两是有关系的被观察者状态改变时,触发观察者的 动作// 被观察者function Observer(){ this.state = ‘默认状态’; this.arr = [];// 用来存储所有的观察者}// 知道谁在 观察自己Observer.prototype.attch = function(s){ // 存储主动观察者 this.arr.push(s);}// 被观察者状态Observer.prototype.setState = function(newState){ this.state = newState; // 只要状态改变就通知所有的观察者,孩子饿了就会朝着爸妈哭 this.arr.forEach(s=>s.update())}// 定义观察者/*** name: 观察者* target: 被观察者**/ function Subject(name,target){ this.name = name; this.target = target;}// 得到状态后的反应Subject.prototype.update = function(newState){ console.log(this.name + ‘观察到状态’ + newState);}let o = new Observer();let s1 = new Subject(‘父亲’,o);let s2 = new Subject(‘母亲’,o);o.attch(s1);o.attch(s2);o.setState(‘饿了’);