Created
December 21, 2010 15:05
-
-
Save JamieMason/750016 to your computer and use it in GitHub Desktop.
A JavaScript function to create namespaces, avoiding the global namespace and keeping any existing or already defined namespaces intact..
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function createNamespace(namespaceString, scope) | |
{ | |
// eg: 'company.section.product.model.version' => ['company', 'section', 'product', 'model', 'version'] | |
var nsNames = namespaceString.split(/[:\.]/g), | |
// store this to save looking it up on every pass of the loop | |
nsNamesLength = nsNames.length, | |
// an optional object to apply the namespace to, eg: myObj.company.* if set, otherwise window.company.* | |
refs = [scope || window], | |
// the current object having a new namespace property added to it | |
nsParent, | |
// the current property/namespace being added to the current object | |
namespace, | |
// loop iterator | |
i; | |
if (nsNamesLength) | |
{ | |
for (i = 0; i < nsNamesLength; i++) | |
{ | |
// get the next namespace/property from the array | |
namespace = nsNames[i]; | |
// get the current object having a new namespace property added to it | |
nsParent = refs[i]; | |
// if nothing exists at this namespace already | |
if (typeof nsParent[namespace] === 'undefined') | |
{ | |
// create it | |
nsParent[namespace] = {}; | |
} | |
// move along the namespace chain to add the next level down onto it | |
refs.push(nsParent[namespace]); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
will output