<script>
const arr = [-1, -2, -3, -4];
const toProxy = new WeakMap();
const toRaw = new WeakMap();
const trigger = function () {
console.log('触发视图更新!');
}
const isObject = function (target) {
return typeof target === 'object' && target !== null;
}
const reactive = function (target) {
if (!isObject(target)) {
return target;
}
const proxy = toProxy.get(target);
if (proxy) {
return proxy;
}
if (toRaw.has(target)) {
return target;
}
const handler = {
set(target, key, value, receiver) {
if (!target.hasOwnProperty(key)) {
trigger();
}
return Reflect.set(target, key, value);
},
get(target, key, receiver) {
const res = Reflect.get(target, key, receiver)
if (isObject(target[key])) {
return reactive(res);
}
return res;
},
deleteProperty(target, key) {
return Reflect.deleteProperty(target, key);
}
}
let observed = new Proxy(target, handler);
toProxy.set(target, observed);
toRaw.set(observed, target);
return observed;
}
const proxy = reactive(arr);
proxy.splice(0, 2);
</script>