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.
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.
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 :)
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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
new
ed up in JavaScript?In C#, one can declare a constructor as private, constraining people to use
ClassName.instance
.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 thatconstructor
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.Thanks Tomek for the follow-up~ 🙏
That sounds like another great reason to use TypeScript 🙂
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 :)