通过Object.defineProperty将属性进行劫持(只会劫持已存在的属性),数组则是通过重写数组方法来实现
// vue响应式原理
let state = {count:0};
let reactiver;
function defineReactive(obj){
for(let key in obj){
let value = obj[key];
let dep = [];
Object.defineProperty(obj,key,{
get() {
if(reactiver){
dep.push(reactiver);
}
return value;
},
set(newValue) {
value = newValue;
//更新试图
dep.forEach((watcher)=>{
watcher();
})
}
})
}
}
defineReactive(state);
const watcher = (fn)=>{
reactiver = fn;
fn();
reactiver = null;
}
watcher(()=>{
document.write(state.count);
})
setTimeout(()=>{
state.count++;
},2000)