What is the simplest/cleanest way to implement singleton pattern in JavaScript?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- suppress a singleton constructor in java with powe
- void before promise syntax
- Keeping track of variable instances
You can do it with decorators like in this example below for TypeScript:
Then you use your singleton like this:
As of this writing, decorators are not readily available in JavaScript engines. You would need to make sure your JavaScript runtime has decorators actually enabled or use compilers like Babel and TypeScript.
Also note that singleton instance is created "lazy", i.e., it is created only when you use it for the first time.
I'm not sure I agree with the module pattern being used as a replacement for a singleton pattern. I've often seen singletons used and abused in places where they're wholly unnecessary, and I'm sure the module pattern fills many gaps where programmers would otherwise use a singleton, however the module pattern is not a singleton.
module pattern:
Everything initialized in the module pattern happens when
Foo
is declared. Additionally, the module pattern can be used to initialize a constructor, which could then be instantiated multiple times. While the module pattern is the right tool for many jobs, it's not equivalent to a singleton.singleton pattern:
short form long form, using module patternIn both versions of the Singleton pattern that I've provided, the constructor itself can be used as the accessor:
If you don't feel comfortable using the constructor this way, you can throw an error in the
if (instance)
statement, and stick to using the long form:I should also mention that the singleton pattern fits well with the implicit constructor function pattern:
What's wrong with this?
The clearest answer should be this one from the book Learning JavaScript Design Patterns by Addy Osmani.
You did not say "in the browser". Otherwise, you can use NodeJS modules. These are the same for each
require
call. Basic example:Note that you cannot access
circle.PI
, as it is not exported.While this does not work in the browser, it is simple and clean.