Skip to content

Instantly share code, notes, and snippets.

@JamieMason
Created December 21, 2010 15:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JamieMason/750016 to your computer and use it in GitHub Desktop.
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..
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]);
}
}
}
@JamieMason
Copy link
Author

var someObject = {}; 
createNamespace('company.section.product.model.version', someObject);

will output

{
    company: {
        section: {
            product: {
                model: {
                    version: {}
                }
            }
        }
    }
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment