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
@CMS and @zzzzBov have both given wonderful answers, but just to add my own interpretation based on my having moved into heavy node.js development from PHP/Zend Framework where singleton patterns were common.
The following, comment-documented code is based on the following requirements:
My code is very similar to @zzzzBov's except I've added a prototype chain to the constructor and more comments that should help those coming from PHP or a similar language translate traditional OOP to Javascripts prototypical nature. It may not be the "simplest" but I believe it is the most proper.
Note that technically, the self-executing anonymous function is itself a Singleton as demonstrated nicely in the code provided by @CMS. The only catch here is that it is not possible to modify the prototype chain of the constructor when the constructor itself is anonymous.
Keep in mind that to Javascript, the concepts of “public” and “private” do not apply as they do in PHP or Java. But we have achieved the same effect by leveraging Javascript’s rules of functional scope availability.
Not sure why nobody brought this up, but you could just do:
I've found the following to be the easiest Singleton pattern, because using the new operator makes this immediately available within the function, eliminating the need to return an object literal:
I think the cleanest approach is something like:
Afterwards, you can invoke the function as
Main key is to Undertand Closure importance behind this.So property even inside the inner function will be private with the help of closure.
var Singleton = function () { var instance;
};
I deprecate my answer, see my other one.
Usually module pattern (see CMS' answer) which is NOT singleton pattern is good enough. However one of the features of singleton is that its initialization is delayed till object is needed. Module pattern lacks this feature.
My proposition (CoffeeScript):
Which compiled to this in JavaScript:
Then I can do following: