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 生效

  

posted @ 2021-03-17 18:14  小短腿奔跑吧  阅读(235)  评论(0编辑  收藏  举报