CHAPTER 5The Singleton Pattern

The singleton is one of the most basic, but useful, patterns in JavaScript, and one that you will probably use more than any other. It provides a way to group code into a logical unit that can be accessed through a single variable. By ensuring that there is only one copy of a singleton object, you know that all of your code makes use of the same global resource.

Singleton classes have many uses in JavaScript. They can be used for namespacing, which reduces the number of global variables in your pages. They can be used to encapsulate browser differences through a technique known as branching, which allows you to use common utility functions without worrying about browser sniffing. Most importantly, they can be used ...

Get Pro JavaScript™ Design Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.