proxy应用场景

断了今生、忘了曾经 提交于 2020-01-21 17:56:14
//场景一:可以修改对象的值let o = {
   name: 'xiaoming',
   price: 190
}
let d = new Proxy(o,{
   get (target,key){
      if(key === 'price'){
          return target[key] + 20
      }else{
          return target[key]
      }
   }
})
console.log(d.price,d.name)
//场景二:不修改其代理的值,只读
let o = {
   name: 'xiaoming',
   price : 190
}

let d = new Proxy(o,{
  get (target,key) {
     return target[key]
  },
  set (target, key, value) {
     return false
  }
})
d.price = 300
console.log(d.price,d.name)

//es5实现只读,缺点:客户和程序员都不能修改
for(let [key] of Object.entries(o)) {
   Object.defineProperty(o,key,{
      writable: false
   })
}
o.price = 300
console.log(d.price,d.name)

//场景三:不破坏数据接口,符合校验规则

 1 let o = {
 2    name: 'xiaoming',
 3    price : 190
 4 }
 5 let validator = (target, key, value) => {
 6    if(Reflect.has(target,key)) {
 7        if(key === 'price') {
 8            if(value > 300) {
 9                return false
10            }else {
11                target[key] = value
12            }
13        }else {
14           target[key] = value
15        }
16     }else{
17         return false
18     }
19 }
20 let d = new Proxy(o, {
21   get (target, key) {
22      return target[key] || ' '
23   },
24   set: validator 
25 })
26 d.price = 203
27 d.name = 'heiei'
28 d.age = 30
29 console.log(d.price,d.name, d.age)//场景4:生成随机编码,只读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)}com.id = '123'console.log(com.id,com2.id)//场景5:如何撤销代理
let o = {
   name: 'xiaoming',
   price : 190
}let d = Proxy.revocable(o, {  get (target, key) {    if(key === 'price') {      return target[key] + 20    }else {      return target[key]    }  }})console.log(d.proxy.price, d)setTimeout(function () {  d.revoke()  setTimeout(function  () {    console.log(d.proxy.price)  },100)},1000)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!