ECMAScript -13 Reflect

Reflect

  • 统一的对象操作API
  • Reflect属于一个静态类,不能通过new的方式构建一个实例对象
  • 只能调用静态方法, 13个静态方法
  • Reflect成员方法就是Proxy处理对象的默认实现

const obj = {
  foo: '123',
  bar: '456'
}

// Proxy中的get/set实现就是调用了Reflect中的静态方法的get/set
const proxy = new Proxy(obj, {
  // 如果我们没有在Proxy中定义get方法,
  // 就相当于在内部定义了get方法,将参数原封不动的传给了Reflect中的对应方法
  get(target, property) {
    console.info('watch logic~')
    return Reflect.get(target, property)
  }
})

console.info(proxy.foo)

Reflect的意义: 提供了一套统一的操作对象的API,统一了对象的操作方式

const person = {
  name: 'tom',
  age: 20,
  gender: 'male'
}
// 🆖🆖🆖 以前的方法 🆖🆖🆖
// console.info('name' in person) // true
// console.info(Object.keys(person)) [ 'name', 'age' ]
// console.info(delete person.name) // true
// console.info(Object.keys(person)) [ 'age' ]

// 🚀🚀🚀 推荐的方法 🚀🚀🚀
console.info(Reflect.has(person, 'name')) // true
console.info(Reflect.deleteProperty(person, 'name')) // true
console.info(Reflect.ownKeys(person)) // [ 'age', 'gender' ]

Reflect apply

/**
 * Reflect.apply
 * 静态方法 Reflect.apply() 通过指定的参数列表发起对目标(target)函数的调用。
 * Reflect.apply(target, thisArgument, argumentsList)
 * target: 目标函数
 * thisArgument: target函数调用时绑定的对象
 * argumentsList: target函数调用时传入的实参列表,该参数应该是一个类数组的对象。
 */

const arr = [1, 2, 3, 4, 5, 6, 7]
const small = Reflect.apply(Math.min, undefined, arr)
const large = Reflect.apply(Math.max, undefined, arr)
info('small:', small) // 1
info('large:', large) // 7

console.info(Reflect.apply(Math.floor, undefined, [1.75])) // 1
console.info(Reflect.apply(String.fromCharCode, undefined, [104, 101, 108, 108, 111])) // hello

posted @ 2020-08-18 17:57  荣光无限  阅读(126)  评论(0)    收藏  举报