An object in an object-oriented language mostly plays one of two roles: It is either a data structure or a component providing a service. In the former case, you tend to make multiple copies (think tree nodes). In the latter case, often only a single copy is needed (think database manager). The singleton pattern (in mathematics, a singleton is a set with exactly one element) has been invented for class-based languages to help them implement components. In such languages, you cannot directly create the component object, you need a class to do so (there are exceptions, but let us ignore them for the sake of this post). With the singleton pattern, you pretend that the class is its single instance and create a one-to-one association between class and instance. The following is an implementation of the singleton pattern in Java [1]:
public class Singleton { public static final Singleton INSTANCE = new Singleton(); // Private constructor prevents external instantiation private Singleton() { } public void amethod() { // ... } }Making the constructor private prevents multiple copies from being made. But more importantly, it prevents improper uses of the class: The natural impulse is to instantiate a class. If the constructor is private, one starts looking for a factory method or a similar construct.
So how about JavaScript? It lets you directly create objects (being one of the few programming languages that allow you to do so) and there is no trickery necessary.
var namespace = { singleton: { amethod: function() { console.log("amethod"); } } }; // Invoke: namespace.singleton.amethod()The namespace is not strictly needed, but a nice touch. Things become slightly more complicated, if you want to create the singleton on demand (lazily).
var namespace = { _singleton: null, getSingleton: function() { if (!this._singleton) { this._singleton = { amethod: function() { console.log("amethod"); } } } return this._singleton; } }; // Invoke: namespace.getSingleton().amethod()If you can afford to only run on newer JavaScript engines, you can use a getter [2] to make the above solution prettier.
var namespace = { _singleton: null, get singleton() { if (!this._singleton) { this._singleton = { amethod: function() { console.log("amethod"); } } } return this._singleton; } }; // Invoke: namespace.singleton.amethod()
Object.defineProperty(namespace, "singleton", { writable: false, configurable: false, value: { ... } });
var namespace = { getSingleton: (function() { // BEGIN iife var singleton; return function() { if (!singleton) { singleton = { amethod: function() { console.log("amethod"); } } } return singleton; }; }()) // END iife }; // Invoke: namespace.getSingleton().amethod()Related reading: