class Dep{
constructor()
{
this.subs=[]; //创建订阅者数组
}
addSub(...wather) //添加订阅者
{
this.subs.push(wather);
}
notice() //通知订阅者数据已经发生改变,需要更新
{
this.subs.forEach(item=>{
console.log(item[0]);
//item.update(); //开始更新数据
});
}
}
class wather{
constructor(name)
{
this.name=name; //创建订阅者
}
update() //更新数据
{
console.log("数据发送了改变,需要更新");
}
}
const obj={
name_:"szp"
};
const dep=new Dep(); //创建订阅者数组
Object.defineProperty(obj,"name",{
set(newValue)
{
//数据发生改变
this.name_=newValue;
dep.notice();
},
get()
{
dep.addSub(new wather("张三"),new wather("李四"),
new wather("王五")); //添加使用了这个属性的订阅者
return this.name_;
}
});
console.log(obj.name);
obj.name="yl";
打印结果 Object { name: "张三" }
this.subs.forEach(item=>{
console.log(item[0]);
//item.update(); //开始更新数据
});
为什么item是数组而不是元素?
因为你放进去的就是数组啊。…wather 它就是个数组。