Namespacing Fundamentals
Namespaces can be found in almost any serious JavaScript application. Unless we’re working with a simple code snippet, it’s imperative that we do our best to ensure that we’re implementing namespacing correctly, as it’s not just simple to pick up, it’ll also avoid third-party code clobbering our own. The patterns we’ll be examining in this section are:
Single global variables
Prefix namespacing
Object literal notation
Nested namespacing
Immediately-invoked Function
Expressions
Namespace injection
Single Global Variables
One popular pattern for namespacing in JavaScript is opting for a single global variable as our primary object of reference. A skeleton implementation of this where we return an object with functions and properties can be found below:
varmyApplication=(function(){function(){//...},return{//...}})();
Although this works for certain situations, the biggest challenge with the single global variable pattern is ensuring that no one else has used the same global variable name as we have in the page.
Prefix Namespacing
One solution to the above problem, as mentioned by Peter
Michaux, is to use prefix namespacing. It’s a simple concept at
heart, but the idea is we select a unique prefix namespace we wish to
use (in this example, myApplication_)
and then define any methods, variables, or other objects after the
prefix as follows:
varmyApplication_propertyA={};varmyApplication_propertyB={};functionmyApplication_myMethod(){//...}
This is effective ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access