代办和反射的定义
挪用 new Proxy() 可罕见替代别的目的 (target) 对象的代办,它假造化了目的,所以两者看起来功用一致。
代办可阻拦JS引擎内部目的的底层对象操纵,这些底层操纵被阻拦后会触发相应特定操纵的圈套函数。
反射 API 以 Reflect 对象的情势涌现,对象中要领的默许特征与雷同的底层操纵一致,而代办能够覆写这类操纵,每个代办圈套对应一个定名和参数都雷同的 Reflect 要领。
运用
基本用法
let target = {};
let p = new Proxy(target, {});
p.a = 37; // 操纵转发到目的
console.log(target.a); // 37. 操纵已被正确地转发
get、set、has、deleteProperty的运用
- get() 要领用于阻拦对象的读取属性操纵
- set() 要领用于阻拦设置属性值的操纵
- has() 要领能够看做是针对 in 操纵的钩子
- deleteProperty() 要领用于阻拦对对象属性的 delete 操纵
let target = {
name: 'target',
color: 'blue',
size: 50,
skill: 'drink'
}
let proxy = new Proxy(target, {
set: function(trapTarget, key, value, receiver) {
// 疏忽不愿望受到影响的已有属性
if(!trapTarget.hasOwnProperty(key)) {
if(isNaN(value)) {
throw new TypeError('属性必需是数字!')
}
}
//增加属性
return Reflect.set(trapTarget, key, value, receiver)
},
get: function(trapTarget, key, receiver) {
if(!(key in receiver)) {
throw new TypeError(key + '属性不存在!')
}
return Reflect.get(trapTarget, key, receiver)
},
has: function(trapTarget, key) {
if(key === 'color') {
return false
}else {
return Reflect.has(trapTarget, key)
}
},
deleteProperty: function(trapTarget, key) {
if(key === 'skill') {
return false
}else {
return Reflect.deleteProperty(trapTarget, key)
}
}
});
//增加一个新属性
proxy.count = 1
console.log(target.count) //1
proxy.name = 'proxy'
console.log(proxy.name) //proxy
console.log(target.name) //proxy
proxy.anotherName = 'proxy' //抛出毛病: 属性必需是数字!
console.log(proxy.age) //抛出毛病:age属性不存在!
console.log('name' in proxy) //true
console.log('color' in proxy) //false
console.log('size' in proxy) //true
let result1 = delete proxy.size
console.log('size' in proxy) //false
console.log('skill' in proxy) //true
let result2 = delete proxy.skill
console.log('skill' in proxy) //true
参考
《深切明白ES6》