As a newbie in Design Patterns in Javascript, I came across the Module Pattern but I don't get something with namespace.
In the namespacing part of Addy Osmani's online book about JS Design Patterns, Addy explains those 5 ways of checking for variable / namespace existence:
// This doesn't check for existence of "myApplication" in
// the global namespace. Bad practice as we can easily
// clobber an existing variable/namespace with the same name
var myApplication = {};
// The following options *do* check for variable/namespace existence.
// If already defined, we use that instance, otherwise we assign a new
// object literal to myApplication.
//
// Option 1: var myApplication = myApplication || {};
// Option 2 if( !MyApplication ){ MyApplication = {} };
// Option 3: window.myApplication || ( window.myApplication = {} );
// Option 4: var myApplication = $.fn.myApplication = function() {};
// Option 5: var myApplication = myApplication === undefined ? {} : myApplication;
What I really don't get is how it solves the problem of naming.
Let's say myApplication is set up before my code tries to use myApplication. Using Option 1 for example (or actually all of the options), does not seem to change anything in case myApplication was already in use but only overwrite the previous values for myApplication:
// Higher in some script, where I don't know about it
var myApplication = 'whatever string or object used by the script';
// A bit of code later, where I come with my little Module Pattern
var myApplication = myApplication || {}; // Using Option 1
myApplication = (function($) {
var myAppVariable = 'blabla';
var myAppFunction = function() {
// Doing a few things here
};
return myAppFunction;
}) (jQuery);
// Using the module
myApplication.myAppFunction();
To me it is very confusing because I don't see how it prevents me for also stepping on other's toes.