Skip to content

Instantly share code, notes, and snippets.

@Williammer
Last active August 29, 2015 14:02
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 Williammer/bd8718513dadcbc6dc02 to your computer and use it in GitHub Desktop.
Save Williammer/bd8718513dadcbc6dc02 to your computer and use it in GitHub Desktop.
jsPatterns.namespace.js
var MYAPP = MYAPP || {};
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[parts[i]] === "undefined") {
parent[parts[i]] = {};
}
parent = parent[parts[i]];
}
//console.log(parent);
return parent;
};
//MYAPP.namespace('modules.module5.module51');
// assign returned value to a local var
var module2 = MYAPP.namespace('MYAPP.modules.module2');
console.log(module2 === MYAPP.modules.module2); // true
// skip initial `MYAPP`
//MYAPP.namespace('modules.module51');
// long namespace
MYAPP.namespace('once.upon.a.time.there.was.this.long.nested.property');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment