What is the simplest/cleanest way to implement the singleton pattern in JavaScript?
Eager initialization: In eager initialization, the instance of Singleton Class is created at the time of class loading, this is the easiest method to create a Singleton class. By making the constructor as private you are not allowing other class to create a new instance of the class you want to create the Singleton.
I think the easiest way is to declare a simple object literal:
var myInstance = { method1: function () { // ... }, method2: function () { // ... } };
If you want private members on your singleton instance, you can do something like this:
var myInstance = (function() { var privateVar = ''; function privateMethod () { // ... } return { // public interface publicMethod1: function () { // All private members are accessible here }, publicMethod2: function () { } }; })();
This has been called the module pattern, and it basically allows you to encapsulate private members on an object, by taking advantage of the use of closures.
If you want to prevent the modification of the singleton object, you can freeze it, using the ES5 Object.freeze
method.
That will make the object immutable, preventing any modification to the its structure and values.
If you are using ES6, you can represent a singleton using ES Modules very easily, and you can even hold private state by declaring variables at the module scope:
// my-singleton.js const somePrivateState = [] function privateFn () { // ... } export default { method1() { // ... }, method2() { // ... } }
Then you can simply import the singleton object to use it:
import myInstance from './my-singleton.js' // ...
I think the cleanest approach is something like:
var SingletonFactory = (function(){ function SingletonClass() { //do stuff } var instance; return { getInstance: function(){ if (instance == null) { instance = new SingletonClass(); // Hide the constructor so the returned object can't be new'd... instance.constructor = null; } return instance; } }; })();
Afterwards, you can invoke the function as
var test = SingletonFactory.getInstance();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With