zl程序教程

您现在的位置是:首页 >  Java

当前栏目

ES6新内置对象Reflect和Proxy的基本使用

2023-02-18 16:30:14 时间

Reflect

为操作对象提供的新API

列举常用的API
const obj = {
    name: 'swt',
    age: 20
  }
  
/*
 * 属性写入
*/
Reflect.set(obj, 'sex', '男')
console.log(obj) // {name: "swt", age: 20, sex: "男"}

/*
 * 属性读取
*/
const a = Reflect.get(obj, 'name')
console.log(a) // swt

/*
 * 属性删除
*/
Reflect.deleteProperty(obj, 'sex')
console.log(obj) // {name: "swt", age: 20}

/*
 * 属性包含
*/
const b = Reflect.has(obj, 'name')
console.log(b) // true

/*
 * 属性遍历
*/
const c = Reflect.ownKeys(obj)
console.log(c) // ["name", "age", "sex"]

Proxy

对象属性读写
const person = {
  name: 'cyw',
  age: 20
}
const personProxy = new Proxy(person, {
  
  get(obj, key) {
    return key in obj ? obj[key] : 'default'
  },

  set(obj, key, value) {
    if(key === 'age') {
      if(!Number.isIntegr(value)) {
        throw new TypeError(`${value} is not an int`)
      }
    }
    obj[key] = value
  }
})

personProxy.age = 10.5 // Uncaught TypeError: 10.5 is not an int
console.log(personProxy.name) // cyw
console.log(personProxy.sex) // default
监视数组操作
const list = []
const listProxy = new Proxy(list, {
  set(obj, key, value) {
    console.log('set', key, value)
    obj[key] = value
    return true
  }
})

listProxy.push(100)
// set 0 100
// set length 1