Skip to content

Instantly share code, notes, and snippets.

@matthanger
Created December 6, 2011 23:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthanger/1440502 to your computer and use it in GitHub Desktop.
Save matthanger/1440502 to your computer and use it in GitHub Desktop.
Namespaces in JavaScript
/**
* Registers the specified namespace, ensuring all parts of the namespace are created. If the namespace
* already exists, it will not be modified.
*
* Usage:
* namespace('foo.bar');
* foo.bar.baz = 'qux';
*
* @param {String} namespace The namespace to register. Namespaces are hierarchal, and are separated by dots.
*/
window.namespace = function(namespace) {
var parts = namespace.split(".");
var root = window;
for(var i=0; i<parts.length; i++) {
root = root[parts[i]] = root[parts[i]] || {};
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment