ES6之Proxy

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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值