鍍金池/ 問答/HTML/ Proxy和Reflect實現(xiàn)單例模式

Proxy和Reflect實現(xiàn)單例模式

class A {
    construct(name) {
        console.log('name: ', name);
        console.log('this: ', this)
        this.name = name;
    }

    testFunction() {
        console.log('testFunction')
    }
}

const singletonify = (OriginalClass) => {
  let i
  return new Proxy(OriginalClass, {
    construct (target, args) {
      console.log('test')
      console.log(args)
      if (!i) i = Reflect.construct(target, args);
      return i
    }
  })
}

singleA = singletonify(A)
a = new singleA()

Reflect.construct(target, args)執(zhí)行的時候為何class A中的construct沒執(zhí)行

回答
編輯回答
淡墨

是...constructor

2017年5月11日 02:57
編輯回答
有點壞
class A {
    constructor(name) {
        console.log('name: ', name);
        console.log('this: ', this)
        this.name = name;
    }

    testFunction() {
        console.log('testFunction')
    }
}

const singletonify = (OriginalClass) => {
  let i
  return new Proxy(OriginalClass, {
    construct (target, args) {
      console.log('test')
      console.log(args)
      if (!i) i = Reflect.construct(target, args);
      return i
    }
  })
}

singleA = singletonify(A)
a = new singleA()
2018年7月26日 09:12