The problem with your code is that it's unintuitive. I expect new
to return a new instance every time. If you still want to do it with your exact code, use zzzzBov's answer.
I propose an alternative API:
function Test() {
// my constructor
}
Test.getInstance = () => {
if (!Test._instance) { Test._instance = new Test(); }
return Test._instance;
}
And call with
const a = Test.getInstance();
const b = Test.getInstance();
console.log(a === b); // true
This doesn't protect you against direct calls to new Test()
though, so it can be bypassed. To truly enforce a single instance, hide Test
behind a closure:
const getTestInstance = (() => {
function Test() {
// my constructor
}
let instance;
const getInstance = () => {
if (!instance) { instance = new Test(); }
return instance;
}
return getInstance;
})();
Now only getTestInstance
is exposed, you can't use new Test()
anymore.
Note: Just writing this code made me puke a little inside my mouth. Please don't use it unless you've evaluated all of your options and know of the price associated with introducing Singletons into your design.