js 单例模式

class Person {
  constructor(name, age) {
    this.name = name
    this.age = age
  }
}

function creataOnlyOneCls(target) {
  let cls;
  return new Proxy(target, {
    construct(target, ...args) {
      if (!cls) {
        cls = new target(...args)//Reflect.construct(target, ...args)
      }
      return cls
    }
  })
}

p1 = creataOnlyOneCls(Person)
console.log(new p1() === new p1())

 

posted @ 2024-07-26 16:21  howhy  阅读(2)  评论(0编辑  收藏  举报