class Singleton { constructor(name) { console.log("实例化"); } }
function CreateSingleton(className) { let instance = null; const proxy = new Proxy(className, { construct(target, args) { console.log("inside proxy constructor", instance); if (!instance) { instance = Reflect.construct(target, args); } return instance; }, }); className.prototype.constructor = proxy; return proxy; } const MySingleton = new CreateSingleton(Singleton); const s = new MySingleton(); const s1 = new MySingleton();
const s2 = new s(); console.log(s === s1);
|