zoukankan      html  css  js  c++  java
  • Proxy 相对于 Object.defineProperty 有哪些优点?

    1. Object.defineProperty 无法一次性监听所有属性, Proxy 可以

    const personInfo = {
      name: 'zhangsan',
      age: 18,
      sex: '男'
    }
    const proxy = new Proxy(personInfo, {
      get(target, key) { },
      set(target, key, newValue) { }
    })
    
    Object.keys(personInfo).forEach(key => {
      Object.defineProperty(personInfo, key, {
        set() { },
        get() { }
      })
    })
    

      

    2. Object.defineProperty 无法监听动态新增的属性, Proxy 可以

    const personInfo = {
      name: 'zhangsan',
      age: 18,
      sex: '男'
    }
    
    const proxy = new Proxy(personInfo, {
      get(target, key) {
        console.log('get', key)
      },
      set(target, key, newValue) {
        target[key] = newValue
        return true
      }
    })
    Object.keys(personInfo).forEach(key => {
      Object.defineProperty(personInfo, key, {
        set() { },
        get() { }
      })
    })

    personInfo.from = '上海'

    console.log(proxy) // Proxy 生效 Object.defineProperty 不生效

      

    3. 可以监听删除的属性?

    const personInfo = {
      name: 'zhangsan',
      age: 18,
      sex: '男'
    }
    
    const proxy = new Proxy(personInfo, {
      get(target, key) {
        console.log('get', key)
      },
      set(target, key, newValue) {
        target[key] = newValue
        return true
      }
    })
    
    Object.keys(personInfo).forEach(key => {
      Object.defineProperty(personInfo, key, {
        set() { },
        get() { }
      })
    })
    
    delete personInfo.age
    console.log(personInfo) // proxy 生效 Object.defineProperty不生效
    

     

    4. 可以监听数组的索引和length属性 

    const personInfo = [1, 2, 3, 4]
    
    const proxy = new Proxy(personInfo, {
      get(target, key) {
        console.log('get', key)
        return key in target ? target[key] : undefined
      },
      set(target, key, newValue) {
        target[key] = newValue
        return true
      }
    })
    
    personInfo.forEach((item, index) => {
      Object.defineProperty(personInfo, index, {
        set() { },
        get() { }
      })
    })
    
    
    personInfo[0] = 8 // 都生效
    personInfo[5] = 6 // proxy 生效
    personInfo.push(99) // proxy 生效
    

      

  • 相关阅读:
    POJ 1987 Distance Statistics(树的点分治)
    rabbitmq-c初探
    [置顶] Android开发实战记录(三)---HelloWorld
    debug连线指令
    Qt之信号连接,你Out了吗?
    hdu-4607-Park Visit
    MySQL 分区表 partition线上修改分区字段,后续进一步学习partition (1)
    如何用正则将多个空格看成一个空格结合spllit()方法将文本数据入库
    hdu 1711 Number Sequence(KMP模板题)
    [leetcode]Unique Paths
  • 原文地址:https://www.cnblogs.com/gqx-html/p/14551013.html
Copyright © 2011-2022 走看看