DEV Community

Discussion on: Singleton in JavaScript

Collapse
 
dance2die profile image
Sung M. Kim • Edited

Thank you for the post Tomek.

I've never implemented singleton in JavaScript and found it interesting 🙂

Is there a way to prevent a singleton class to be newed up in JavaScript?
In C#, one can declare a constructor as private, constraining people to use ClassName.instance.

Collapse
 
tomekbuszewski profile image
Tomek Buszewski

Hi, and thanks foe your kind words!

JavaScript doesn't have private and public distinction (yet), so the short answer is - no.

The long one is - you can have private methods in TypeScript (and, private constructor). I've created a simple demo and – while TypeScript linter shouts that this is an error (noting that constructor is indeed private), this gets compiled to JavaScript as a regular class that can have multiple instances. So I guess it's the compiler's job to fail here.

Collapse
 
dance2die profile image
Sung M. Kim

Thanks Tomek for the follow-up~ 🙏

That sounds like another great reason to use TypeScript 🙂

Thread Thread
 
tomekbuszewski profile image
Tomek Buszewski

Yes, TypeScript is a great tool and I use it recently for almost everything. The best thing is, it's JavaScript superset, so you don't really have to know everything and can just build your knowledge while working on a project. Create a plain JS code then slowly fill the type coverage as you go :)