进阶技巧
Proxy 与 Reflect
Proxy 拦截对象操作、Reflect 反射 API、响应式原理
Proxy 与 Reflect
Proxy 拦截对象的基本操作,Reflect 提供对应的反射方法。Vue 3 的响应式系统就是用 Proxy 实现的。
学完本章你将: 掌握 Proxy 拦截器、Reflect API、响应式原理。
Proxy 基础
javascript
const target = { name: "小明", age: 25 };
const handler = {
get(obj, prop) {
console.log(`读取 ${prop}`);
return obj[prop];
},
set(obj, prop, value) {
console.log(`设置 ${prop} = ${value}`);
obj[prop] = value;
return true; // 必须返回 true 表示成功
},
};
const proxy = new Proxy(target, handler);
proxy.name; // 读取 name → "小明"
proxy.age = 30; // 设置 age = 30
常用拦截器
javascript
const handler = {
get(obj, prop) { }, // 读取属性
set(obj, prop, value) { }, // 设置属性
has(obj, prop) { }, // in 运算符
deleteProperty(obj, prop){}, // delete 运算符
ownKeys(obj) { }, // Object.keys/for...in
apply(target, thisArg, args) { }, // 函数调用
construct(target, args) { }, // new 操作符
};
简易响应式系统
javascript
function reactive(target, onChange) {
return new Proxy(target, {
set(obj, prop, value) {
obj[prop] = value;
onChange(prop, value);
return true;
},
});
}
const state = reactive({ count: 0 }, (key, val) => {
console.log(`状态变化: ${key} = ${val}`);
});
state.count++; // 状态变化: count = 1
Reflect —— 更优雅的反射
javascript
// 传统方式
delete obj.name;
"name" in obj;
// Reflect 方式(更一致、有返回值)
Reflect.deleteProperty(obj, "name"); // true/false
Reflect.has(obj, "name"); // true/false
Reflect.ownKeys(obj); // 所有自有键