Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ES6 Reflect #25

Open
ChuChencheng opened this issue Jan 13, 2020 · 0 comments
Open

ES6 Reflect #25

ChuChencheng opened this issue Jan 13, 2020 · 0 comments

Comments

@ChuChencheng
Copy link
Owner

概念

Reflect 是一个内置的对象,提供拦截操作的方法,与 Proxy 的 handlers 方法相同。

可以配合 Proxy 使用,在 handlers 中通过 Reflect 获取默认行为,在完成默认行为的基础上做修改。

静态方法

与 Proxy handlers 相同的 13 个方法。

应用

使用 Proxy 实现观察者模式:

/** 观察者集合 */
const observerSet = new Set()

// 观察者模式方法
const observe = (fn) => observerSet.add(fn)
const observable = (obj) => new Proxy(obj, { set })
const set = (target, key, value, receiver) => {
  // 先完成默认行为
  const result = Reflect.set(target, key, value, receiver)
  // 通知观察者变化
  observerSet.forEach((observer) => observer())
  return result
}

/** 观察目标 */
const person = observable({
  name: 'a',
  age: 18,
})

/** 观察者 */
const print = () => {
  console.log(`${person.name}, ${person.age}`)
}

observe(print)

person.name = 'b' // b 18

参考

http://es6.ruanyifeng.com/#docs/reflect

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant