ES6之Proxy
Proxy用法
Proxy 用于修改某些操作的默认行为,可以理解成,在目标对象之前架设一层“拦截”,外界对该对象的访问,都必须先通过这层拦截,因此提供了一种机制,可以对外界的访问进行过滤和改写。
let o={
price:190,
name:'xiaoming'
}
let d=new Proxy(o,{
get(target,key){
if(key==='price'){
return target[key]=210
}else{
return target[key]
}
}
})
console.log(d.price,d.name)
//210 xiaoming
用来拦截某个属性的赋值操作,把数据变成只读。
let o={
price:190,
name:'xiaoming'
}
let d=new Proxy(o,{
get(target,key){
if(key==='price'){
return target[key]
},
set(target,key,value){
return false
}
})
d.price=300
console.log(d.price)
//190
校验处理
不能破坏数据结构,拦截无效数据。
let o={
price:190,
name:'xiaoming'
}
//解耦
let validator=(target,key,value)=>{
if(Reflect.has(target,key)){
if(key==='price'){
if(value>300){
return false
}else{
target[key]=value
}
}else{
target[key]=value
}
}else{
return false
}
}
let d=new Proxy(o,{
get(target,key){
return targrt[key]
}
set:validator
})
d.price=200 //200
d.price=301 //190
d.age=400
console.log(d.age) //''
错误上报
//监听错误
window.addEventListen('error',(e)=>{
console.log(e.message)
//上报加载错误
report(e)
},true)
let o={
price:190,
name:'xiaoming'
}
//校验规则
let validator=(target,key,value)=>{
if(Reflect.has(target,key)){
if(key==='price'){
if(value>300){
//不满足规则就要触发错误
throw new TypeError('price exceed 300')
}else{
target[key]=value
}
}else{
target[key]=value
}
}else{
return false
}
}
let d=new Proxy(o,{
get(target,key){
return targrt[key]
}
set:validator
})
d.price=301 //抛出错误
识别每个组件
每次生成时是随机的,不同的实例对象之间是唯一的,并且是只读的。
class Component{
constructor(){
this.proxy=new Proxy({
id:Math.random().toString(36).slice(-8)
},{})
}
get (id){
return this.proxy.id
}
}
let com=new Component()
let com2=new Component()
for(let i=0;i<10;i++){
console.log(com.id,com2.id)
}
//输出两个十次相同的数 6uygf85f 21fsfsg0
com.id='abc'
//输出结果不变
撤销代理
let o={
price:190,
name:'xiaoming'
}
let d= Proxy.revocable(o,{
get(target,key){
if(key==='price'){
return target[key]=210
}else{
return target[key]
}
}
})
console.log(d.proxy.price,d)
setTimeout(function(){
d.revoke() //销毁
setTimeout(function(){
console.log(d.proxy.price)
},100) //数据已销毁,无法读出
},1000)