qiuhongbingo / blog

Writing something in Issues.
https://github.com/qiuhongbingo/blog/issues
3 stars 0 forks source link

Proxy 简单场景的应用 #17

Open qiuhongbingo opened 4 years ago

qiuhongbingo commented 4 years ago
// 场景一:防止非构造函数实例化的调用
class Person {
  constructor(name) {
    this.name = name
  }
}

let proxyPersonClass = new Proxy(Person, {
  apply(target, context, args) {
    /**
     * 针对 call 1
     * 对 Person 构造函数进行代理,这样就可以防止非构造函数实例化的调用
     */
    throw new Error(`hello: Function ${target.name} cannot be invoked without 'new'`)

    /**
     * 针对 call 2
     * 也可以静默处理非构造函数实例化的调用,将其强制转换为 new 调用
     */
    // return new (target.bind(context, ...args))()
  }
})

// call 1
// proxyPersonClass('bingo') // Uncaught Error: hello: Function Person cannot be invoked without 'new'

// call 2
// proxyPersonClass('bingo')

// call 3
new proxyPersonClass('bingo') // { name: 'bingo' }

// 场景二:实现断言测试
const assert = new Proxy(
  {},
  {
    set(target, warning, value) {
      if (!value) {
        console.error(warning)
      }
    }
  }
)

const bingo = { age: 26 }
assert['bingo is older than 18!!!'] = 18 > bingo.age // Error: bingo is older than 18!!!