Skip to content

Instantly share code, notes, and snippets.

@corymartin
Last active December 18, 2015 10:39
Show Gist options
  • Save corymartin/5770583 to your computer and use it in GitHub Desktop.
Save corymartin/5770583 to your computer and use it in GitHub Desktop.
Creates a namespace based upon a string representation of a namespace. Adapted from a similar function in JavaScript Patterns by Stoyan Stefanov.
/*
* Creates a namespace based upon a string representation of a namespace.
* Adapted from a similar function in JavaScript Patterns by Stoyan Stefanov.
*
* @param {String} ns String representation of namespace. Eg, 'foo.bar.baz.goo'
* @returns {Object} Last object created in the namespace.
*/
void function() {
var root = 'myapp';
window[root] = window[root] || {};
function namespace(ns) {
var parts = ns.split('.');
if (parts[0] === root) {
parts = parts.slice(1);
}
var parent = window[root];
for (var i = 0; i < parts.length; i++) {
if (parent[parts[i]] == null) {
parent[parts[i]] = {};
}
parent = parent[parts[i]];
}
return parent;
};
namespace('util').namespace = namespace;
}();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment