1.先创建singleton 通用函数
function singleton(className) {
let ins;
return new Proxy(className, {
construct(target, args) {
if (!ins) {
ins = new target(...args)
}
return ins
}
})
}
用法,通过多次new 发现 constructor中的log 只执行一次,单例模式实现
class Test {
constructor(...a) {
console.log(a)
}
}
const newTest = singleton(Test)
let res = new newTest(1, 2, 3)
let res2 = new newTest(1, 2, 3)
res