Proxy概述
var obj = new Proxy({}, {
get: function(target, key, receiver){
console.log(`getting ${key}!`);
return Reflect.get(target, key , receiver);
},
set: function(target, key, value, receiver) {
console.log(`setting ${key} : ${value}`);
return Reflect.set(target, key, value + 1, receiver);
}
});
obj.count = 1;
console.info(obj.count);
// setting count : 1
// getting count!
// 2
- Proxy原意代理
- 可以用来修改某些操作的默认行为,等同于在语言层面作出修改,属于一种元编程
语法
var proxyobj = new Proxy( target, handler );
通过Proxy构造函数来生成代理对象
target是代码的原始对象
handler是代理处理代码, 用来定制拦截行为;也是对象
支持的拦截操作一览
- get(target, propKey, receiver)
- set(target, propKey, propValue, receiver)
- has(target, propKey)
- deleteProperty(target, propKey)
- enumerate(target)
- ownKeys(target)
- getOwnPropertyDescriptor(target, propKey)
- defineProperty(target, propKey, propDesc)
- preventExtensions(target)
- getPrototypeOf(target)
- isExtensible(target)
- setPrototypeOf(target, proto)
- apply(target, object, args)
- construct(target, args, proxy)
Proxy.revocable()
- Proxy.revocable方法可返回一个可取消的Proxy实例
let target = {};
let handler = {};
let {proxy, revoke} = Proxy.revocable( target, handler );
proxy.foo = 123;
proxy.foo // 123
revoke(); //取消proxy实例
proxy.foo // TypeError:Revoked
Reflect概述
- 将某些明显属于语言内部的方法,放到Reflect对象上;比如:Object.defineProperty
- 修改某些Object方法的返回结果,让其变得更合理。比如
try{
Object.defineProperty(target, property, atributes);
}catch(err){}
if(Reflect.defineProperty(target,property, attributes) ) {
}
- 放Object操作行为变为函数行为 delete in
- Reflect对象的方法与Proxy对象的方法一一对应
Reflect对象的方法
- Reflect.apply(target,thisArg,args)
- Reflect.construct(target,args)
- Reflect.get(target,name,receiver)
- Reflect.set(target,name,value,receiver)
- Reflect.defineProperty(target,name,desc)
- Reflect.deleteProperty(target,name)
- Reflect.has(target,name)
- Reflect.ownKeys(target)
- Reflect.enumerate(target)
- Reflect.isExtensible(target)
- Reflect.preventExtensions(target)
- Reflect.getOwnPropertyDescriptor(target, name)
- Reflect.getPrototypeOf(target)
- Reflect.setPrototypeOf(target, prototype)