What is the simplest/cleanest way to implement singleton pattern in JavaScript?
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, it basically allows you to encapsulate private members on an object, by taking advantage of the use of closures.
UPDATE: I would like to add that 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.
Additionally I would like to mention that 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'
// ...