Skip to content

Instantly share code, notes, and snippets.

@stamat
Last active December 16, 2015 03:39
Show Gist options
  • Save stamat/5371124 to your computer and use it in GitHub Desktop.
Save stamat/5371124 to your computer and use it in GitHub Desktop.
JavaScript namespace declaration
var namespace = function(str, root) {
var chunks = str.split('.');
if(!root)
root = window;
var current = root;
for(var i = 0; i < chunks.length; i++) {
if (!current.hasOwnProperty(chunks[i]))
current[chunks[i]] = {};
current = current[chunks[i]];
}
return current;
};
// ----- USAGE ------
namespace('ivar.util.array');
ivar.util.array.foo = 'bar';
alert(ivar.util.array.foo);
namespace('string', ivar.util);
ivar.util.string.foo = 'baz';
alert(ivar.util.string.foo);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment