本文链接:https://blog.csdn.net/jiang7701037/article/details/79027566
代码:
原始数字:
平方:
立方:
三个数之和:
observer.js文件的内容
//1、定义观察者模式的对象(模板)
var observer = {
//订阅
addSubscriber:function(callback){
this.subscribers.push(callback);
},
//退订
removeSubscriber:function(callback){
let index = this.subscribers.indexOf(callback);
this.subscribers.splice(index,1);
},
//发布
publish:function(what){
for(let i in this.subscribers){
if(typeof this.subscribers[i]==="function"){
this.subscribers[i](what);
}
}
},
//让指定对象具备观察者的所有功能
make:function(obj){
for(let key in this){
obj[key] = this[key];
}
obj.subscribers = [];
}
}