对象 proxy
const hh = { name:"zhangsan", age: 18 };
const proxy = new Proxy(hh, {
get(target, key) {
if (key in target) {
return target[key];
} else {
return "没有这个属性";
}
},
set(target, key, value) {
if (key in target) {
target[key] = value;
} else {
return "没有这个属性";
}
return true;
},
});
console.log(proxy.name);
函数 proxy
// 函数 proxy
function factorial(n) {
return n === 1 ? 1 : n * factorial(n - 1);
}
let proxy = new Proxy(factorial, {
apply(func, obj, args) {
console.time("start");
func.apply(this, args);
console.timeEnd("start");
},
});
proxy(5);
数组
let arr = [1, 2, 3];
let proxy = new Proxy(arr, {
get(target, key, receiver) {
// 很容易玩坏
return target[key];
},
});
console.log(proxy[0]);