Chapter 11. Namespacing Patterns
In this chapter, we will explore patterns for namespacing in JavaScript. Namespaces can be considered a logical grouping of code units under a unique identifier. You can reference the identifier in many namespaces, and each identifier can contain a hierarchy of nested (or sub) namespaces.
In application development, we employ namespaces for many important reasons. JavaScript namespaces help us avoid collisions with other objects or variables in the global namespace. They’re also handy for helping organize blocks of functionality in a codebase so that it can be more easily referenced and used.
Namespacing any serious script or application is critical because it’s crucial to safeguard our code from breaking in the event of another script on the page using the same variable or method names we are. With the number of third-party tags regularly injected into pages, this can be a common problem we all need to tackle at some point in our careers. As a well-behaved “citizen” of the global namespace, it’s also imperative that we try our best not to prevent other developers’ scripts from executing due to the same issues.
While JavaScript doesn’t have built-in support for namespaces like other languages, it does have objects and closures that you can use to achieve a similar effect.
Namespacing Fundamentals
You can find namespaces in almost any serious JavaScript application. Unless we’re working with a simple code snippet, we must do our best to ensure ...
Get Learning JavaScript Design Patterns, 2nd Edition 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.