Proxy:
- 用法
new Proxy(obj, handler)
- Proxy 中接受的 Receiver 形参表示代理对象本身或者继承与代理对象的对象
Reflect:
-
Reflect.get(target, key, receiver)
等价target[key].call(receiver)
保证上下文this指向正确 - Reflect 中传递的 Receiver 实参表示修改执行原始操作时的 this 指向。
proxy代理对象
var obj = {
a: 1,
b: 2
};
var proxy = new Proxy(obj, {
get: function(target, key, receiver) {
return Reflect.get(target, key, receiver);
},
set: function(target, key, value, receiver) {
return Reflect.set(target, key, value, receiver);
}
});
//打印出来 proxy对象
/*
{
deleteProperty: ƒ deleteProperty(target, key),
get: ƒ (target, key, receiver),
has: ƒ has(target, key),
ownKeys: ƒ ownKeys(target),
set: ƒ (target, key, value, receiver),
a: 1,
b: 2,
...
}
*/
proxy代理数组
var arr = [1,2,3]
var proxy = new Proxy(arr, {
get: function (target, key, receiver) {
return Reflect.get(target, key, receiver);
},
set(target, key, value, receiver){
return Reflect.set(target, key, value, receiver);
}
})
//打印出来 proxy对象
/*
{
0: 1,
1: 2,
2: 3,
deleteProperty: ƒ deleteProperty(target, key),
get: ƒ (target, key, receiver),
has: ƒ has(target, key),
ownKeys: ƒ ownKeys(target),
set: ƒ (target, key, value, receiver),
...
}
*/