-
Notifications
You must be signed in to change notification settings - Fork 242
Nested Namespacing Plugin Pattern
From Learning JavaScript Design Patterns, a book by Addy Osmani.
As we've previously covered in the book, namespacing our code is a way to avoid collisions with other objects and variables in the global namespace. They’re important because we want to safeguard our plugin from breaking in the event that another script on the page uses the same variable or plugin names as ours. As a good citizen of the global namespace, we must also do our best not to prevent other developers scripts from executing because of the same issues.
JavaScript doesn't really have built-in support for namespaces as other languages do, but it does have objects that can be used to achieve a similar effect. Employing a top-level object as the name of our namespace, we can easily check for the existence of another object on the page with the same name. If such an object does not exist, then we define it; if it does exist, then we simply extend it with our plugin.
Objects (or, rather, object literals) can be used to create nested namespaces, such as namespace.subnamespace.pluginName
and so on. But to keep things simple, the namespacing boilerplate below should show us everything we need to get started with these concepts.
- “Namespacing in JavaScript,” Angus Croll
- “Use Your $.fn jQuery Namespace,” Ryan Florence
- “JavaScript Namespacing,” Peter Michaux
- “Modules and namespaces in JavaScript,” Axel Rauschmayer