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
Isn't this a singleton too?
Singleton in javascript is achieved using Module pattern and closures. Below is the code which is pretty much self-explanatory -
I think the easiest way is to declare a simple object literal:
If you want private members on your singleton instance, you can do something like this:
This is has been called the module pattern, it basically allows you to encapsulate private members on an object, by taking advantage of the use of closures.
I needed several singletons with:
and so this was what I came up with:
args must be Array for this to work so if you have empty variables, just pass in []
I used window object in the function but I could have passed in a parameter to create my own scope
name and construct parameters are only String for window[] to work but with some simple type-checking, window.name and window.construct are also possible.
I got this example from JavaScript Patterns Build Better Applications with Coding and Design Patterns By Stoyan Stefanov's book in case you need some simple implementation class like singltone object you can use immediate function as following:
And you can check this example by following test case:
This approaches passes all test cases while private static implementation will fail when prototype extension is used (it can be fixed but it will not be simple) and public static implementation less advisable due to instance is exposed to the public.
jsFiddly demo.
There is more than one ways to skin a cat :) Depending on your taste or specific need you can apply any of the proposed solutions. I personally go for CMS' first solution whenever possible (when you don't need privacy). Since the question was about the simplest and cleanest, that's the winner. Or even:
This (quote from my blog) ...
doesn't make much sense (my blog example doesn't either) because it doesn't need any private vars, so it's pretty much the same as: