## JavaScript Proxy:赋予对象超能力的元编程利器(注释增强版)
const proxy = new Proxy(target, handler);
### 二、常用陷阱方法实战(带注释)
1. **安全属性访问**
```javascript
const validator = {
/**
* 属性访问拦截器
* @param {object} target - 被代理的原始对象
* @param {string|symbol} prop - 被访问的属性名
*/
get(target, prop) {
// 使用in运算符检查原型链
return prop in target
? target[prop] // 属性存在时返回正常值
: `属性 ${prop} 不存在`;
}
};
const person = { name: 'Alice' };
const proxy = new Proxy(person, validator);
console.log(proxy.age);
- 数据验证拦截
const ageValidator = {
set(target, prop, value) {
if (prop === 'age') {
if (!Number.isInteger(value)) {
throw new TypeError('年龄需为整数');
}
if (value < 0) {
throw new RangeError('年龄不能为负数');
}
}
target[prop] = value;
return true;
}
};
const user = new Proxy({}, ageValidator);
user.age = 25;
user.age = "25";
- 函数调用监控
const logger = {
apply(target, thisArg, args) {
console.log(`调用函数 ${target.name},参数:${args}`);
return target.apply(thisArg, args);
}
};
function sum(a, b) { return a + b; }
const loggedSum = new Proxy(sum, logger);
loggedSum(3, 4);
三、高级应用场景(带实现注释)
- 响应式系统核心
const reactive = (obj) => {
return new Proxy(obj, {
get(target, prop) {
track(target, prop);
return Reflect.get(...arguments);
},
set(target, prop, value) {
trigger(target, prop);
return Reflect.set(...arguments);
}
});
};
const dep = new Map();
function track(target, prop) {
console.log(`追踪: ${target.constructor.name}.${prop}`);
}
function trigger(target, prop) {
console.log(`触发更新: ${target.constructor.name}.${prop}`);
}
- 智能API缓存
const createCachedApi = (apiFunc) => {
const cache = new Map();
return new Proxy(apiFunc, {
apply(target, thisArg, args) {
const key = JSON.stringify(args);
if (cache.has(key)) {
console.log('从缓存读取');
return cache.get(key);
}
const result = target(...args);
cache.set(key, result);
return result;
}
});
};
const fetchData = (url) => fetch(url).then(r => r.json());
const cachedFetch = createCachedApi(fetchData);
- 虚拟属性扩展
const virtualProperties = {
get(target, prop) {
if (prop === 'fullName') {
return `${target.firstName} ${target.lastName}`;
}
return target[prop];
}
};
const person = new Proxy(
{ firstName: 'John', lastName: 'Doe' },
virtualProperties
);
console.log(person.fullName);
console.log(person.firstName);
四、注意事项(增强说明)
- 性能优化策略
const heavyProxy = new Proxy({}, {
get(target, prop) {
performHeavyCalculation();
return Reflect.get(...arguments);
}
});
- 安全撤销示例
const {proxy, revoke} = Proxy.revocable({}, {});
proxy.name = 'test';
revoke();
proxy.name;