DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Coding
  3. JavaScript
  4. The Singleton pattern in JavaScript: not needed

The Singleton pattern in JavaScript: not needed

Axel Rauschmayer user avatar by
Axel Rauschmayer
·
Apr. 13, 11 · Interview
Like (0)
Save
Tweet
Share
6.15K Views

Join the DZone community and get the full member experience.

Join For Free

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 methodsObject.preventExtensions(), Object.seal(), andObject.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

 

From http://www.2ality.com/2011/04/singleton-pattern-in-javascript-not.html

Singleton pattern JavaScript

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Reliability Is Slowing You Down
  • What Are the Benefits of Java Module With Example
  • Monolithic First
  • Introduction to Spring Cloud Kubernetes

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: