Skip to content

Instantly share code, notes, and snippets.

@tyom
Created January 26, 2012 15:56
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 tyom/1683450 to your computer and use it in GitHub Desktop.
Save tyom/1683450 to your computer and use it in GitHub Desktop.
JS Namespace function
var MYAPP = MYAPP || {};
// Namespacing function. Simplifies the process of namespacing
// Usage: MYAPP.namespace('MYAPP.path.to.myModule'); or MYAPP.namespace('path.to.myModule');
MYAPP.namespace = function(ns_string) {
var parts = ns_string.split('.'),
parent = MYAPP,
i;
// strip redundant leading global
if(parts[0] === 'MYAPP') {
parts = parts.slice(1);
}
for(i = 0; i < parts.length; i += 1) {
// create a property if it doesn't exist
if(typeof parent[parent[i]] === 'undefined') {
parent[parts[i]] = {};
}
parent = parent[parts[i]];
}
return parent;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment