const bucket = new WeakMap();
let activeEffect = null;
function reactive(data){
const obj = new Proxy(data, {
get(target, key){
if(!activeEffect){
return target[key]
}
//取出与target绑定的map
let depsMap = bucket.get(target);
if(!depsMap){
bucket.set(target, (depsMap = new Map()));
}
//取出与key对应的副作用函数
let depsEffets = depsMap.get(key);
if(!depsEffets){
depsMap.set(key, (depsEffets = new Set()));
}
depsEffets.add(activeEffect);
return target[key];
},
set(target, key, value){
target[key] = value;
const depsMap = bucket.get(target);
if(!depsMap){
return
}
const depsEffets = depsMap.get(key);
depsEffets&&depsEffets.forEach(fn=>fn());
return true;
}
})
return obj;
}
const effect = (fn)=>{
activeEffect = fn;
fn();
};
const obj1 = reactive({name: "李翔"})
const obj2 = reactive({age: 18})
effect(()=>{
console.log('obj1', obj1.name)
})
effect(()=>{
console.log('obj2', obj2.age)
})
setTimeout(()=>{
obj1.name = "dora"
}, 1000)
setTimeout(()=>{
obj2.age = 20
}, 2000)
console