2.1 拦截操作种类
Proxy
可以拦截的操作包括:get
、set
、has
、deleteProperty
、apply
等。
2.2 示例
const target = {
name: 'Alice',
age: 30
};
const handler = {
get: function (target, prop) {
console.log(`Getting property "${prop}"`);
return target[prop];
},
set: function (target, prop, value) {
console.log(`Setting property "${prop}" to "${value}"`);
target[prop] = value;
}
};
const proxy = new Proxy(target, handler);
proxy.name; // 输出: Getting property "name", 然后输出 "Alice"
proxy.age = 31; // 输出: Setting property "age" to "31"