Created
October 11, 2013 08:23
-
-
Save dannycallaghan/6931394 to your computer and use it in GitHub Desktop.
Generic Namespace Function. From 'JavaScript Patterns' (O'Reilly) by Stoyan Stefanov.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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