2011-04-12

The Singleton pattern in JavaScript: not needed

This post argues that the singleton pattern is usually not needed in JavaScript, because you can directly create objects. It then slightly backpedals from that position and shows you code skeletons that you can use if your needs go beyond the basics.

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()

Security considerations

The above presented solutions might be too sloppy for your taste. I would argue that they are relatively easy to understand and obvious to use, but for the more paranoid among us (and there are situations where that paranoia is justified), the following enhancements are conceivable. Note that that usually makes the code harder to understand.
  • Prevent copies from being made: Programmers coming from Java to JavaScript seem more concerned about this than others. You do this by completely hiding the instance’s constructor. Consult [3] for an in-depth treatise.
  • Prevent the singleton from being exchanged: An attacker might try to swap your singleton for their implementation. By making property singleton in the namespace read-only and non-configurable (i.e., the read-only setting cannot be changed), you can prevent that.
        Object.defineProperty(namespace, "singleton",
            { writable: false, configurable: false, value: { ... } });
    
  • Prevent changes to the singleton: The methods Object.preventExtensions(), Object.seal(), and Object.freeze() give you (increasingly thorough) means to lock down an object [4].
  • Keep data private: This again seems to be most important to Java people. See below for a solution.
By wrapping an immediately-invoked function expression (IIFE, [5]) around the singleton, you can hide the variable holding the singleton.
    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:
  1. The Singleton pattern and its simplest implementation in Java
  2. JavaScript Getters and Setters
  3. The singleton design pattern in JavaScript
  4. Object.freeze Function (JavaScript)
  5. JavaScript variable scoping and its pitfalls
Flattr

No comments: