Skip to content

Instantly share code, notes, and snippets.

@dannycallaghan
Created October 11, 2013 08:23
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 dannycallaghan/6931394 to your computer and use it in GitHub Desktop.
Save dannycallaghan/6931394 to your computer and use it in GitHub Desktop.
Generic Namespace Function. From 'JavaScript Patterns' (O'Reilly) by Stoyan Stefanov.
/* Namespace Function */
var MYAPP = MYAPP || {};
MYAPP.namespace = function ( ns_string ) {
var parts = ns_string.split( '.' ),
parent = MYAPP, i;
if ( parts[ 0 ] === "MYAPP" ) {
parts = parts.slice( 1 );
}
for ( i = 0; i < parts.length; i += 1 ) {
if ( typeof parent[ parts[ i ] ] === "undefined" ) {
parent[ parts[ i ] ] = {};
}
parent = parent[ parts[ i ] ];
}
return parent;
};
MYAPP.namespace( 'MYAPP.modules.module2' );
MYAPP.namespace( 'modules.module51' ); // skipping initial 'MYAPP'
MYAPP.namespace( 'once.upon.a.time.there.was.this.long.nested.property' );
/* produces:
MYAPP {
modules : {
module2 : {},
module : ()
},
once : {
upon : {
a : {
time : {
...
}
}
}
}
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment