Sunday, 11 September, 2016 UTC


Summary

The Singleton pattern is to ensure there is only one instance of the class that exists. In the case it does exist it returns a reference to that object. This is normally achieved by a method belonging to the class to create an instance.
Singleton in JavaScript is useful to for providing a single point of access to functions which are isolated from the global namespace.
Example are written in ES2015 syntax.
Basic and typical implementation of a Singleton in JavaScript using an object literal:
const aSingleton = { propA: 'some value', propB: 3, someMethod() { return 'some text'; } };
Maybe you want to have private fields and functions? These can be encapsulated inside of a closure and return a object literal to expose the public interface.
const aSingleton = () => { const privateField = 'abc'; function privateFunction(){ return 'some private data ' + privateField; }; return { publicMethod() { return privateFunction(); } }; };
Another technique is to instantiate the class when it’s needed which can help save on resource:
const ASingleton = (() => { let isInstance; function initSingleton() { return { aProp: 'with value', publicMethod() { return 'something valuable'; } }; } return { getInstance() { if(!isInstance){ isInstance = initSingleton(); } return isInstance; } }; }()); ASingleton.getInstance().publicMethod();