用Proxy拦截class,这种骚操作闻所未闻!

一个突发奇想,如果要拦截class的属性变化,除了用defineProperty进行重写,难道不能用Proxy吗?于是,产生了下面这段代码。

class A {
  name = 'aaa'
  age = 0
  constructor() {
    return new Proxy(this, {
      get: (_, key) => this[key],
      set: (_, key, value) => {
        console.log(key, value)
        this[key] = value
        return true
      },
    })
  }
  say() {
    console.log(this.name, this.age)
  }
  update(key, value) {
    this[key] = value
  }
}

在构造函数中return new Proxy(this)真是够风骚的操作。

已有1条评论
  1. rxliuli 2020-12-01 12:04

    一般吾辈会用 class static function 或者注解来解决