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
Short answer:
Because non-blocking nature of JavaScript, Singletons in JavaScript are really ugly in use. Global variables will give you one instance through whole application too without all these callbacks, module pattern gently hides internals behind the interface. See @CMS answer.
But, since you wanted a singleton…
Usage:
Explanation:
Singletons give you more than just one instance through whole application: their initialization is delayed till first use. This is really big thing when you deal with objects whose initialization is expensive. Expensive usually means I/O and in JavaScript I/O always mean callbacks.
Don't trust answers which give you interface like
instance = singleton.getInstance()
, they all miss the point.If they don't take callback to be run when instance is ready, then they won't work when initializer does I/O.
Yeah, callbacks always look uglier than function call which immediately returns object instance. But again: when you do I/O, callbacks are obligatory. If you don't want to do any I/O, then instantiation is cheap enough to do it at program start.
Example 1, cheap initializer:
Example 2, initialization with I/O:
In this example
setTimeout
fakes some expensive I/O operation. This illustrates why singletons in JavaScript really need callbacks.How about this way, just insure the class can not new again.
By this, you can use the
instanceof
op, also, you can use the prototype chain to inherit the class,it's a regular class, but can not new it,if yuu want to get the instance just usegetInstance
If you don't want to expose the
instance
member, just put it into a closure.Module pattern: in "more readable style". You can see easily which methods are publics and which ones are privates
now you can use publics methods like
module.method2(); //-> I'm calling a private method over a public method alert("hi im a private method")
http://jsfiddle.net/ncubica/xMwS9/
I think I have found the cleanest way to program in JavaScript, but you'll need some imagination. I got this idea from a working technique in the book "javascript the good parts".
Instead of using the new keyword, you could create a class like this:
You can instantiate the above object by saying:
Now with this work method in mind you could create a singleton like this:
Now you can get your instance by calling
I think this is the neatest way as the complete "Class" is not even accessible.
I believe this is the simplest/cleanest and most intuitive way though it requires ES7:
The source code is from: adam-bien.com
The following works in node v6
We test: