SOURCE

const bucket = new WeakMap();

let activeEffect = null;

//封装收集副作用函数
function track(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);
}
//封装触发副作用函数
function trigger(target, key, value){
    const depsMap = bucket.get(target);
    if(!depsMap){
        return
    }
    const depsEffets = depsMap.get(key);
    depsEffets&&depsEffets.forEach(fn=>fn());
}

function reactive(data){
    const obj = new Proxy(data, {
        get(target, key){
            track(target, key);
            return target[key];
        },
        set(target, key, value){
            target[key] = value;
            trigger(target,key,value);
            return true;
        }
    })
    return obj;
}

const effect = (fn)=>{
    activeEffect = fn;
    fn();
    activeEffect = null;
};


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 命令行工具 X clear

                    
>
console