Created
December 6, 2012 01:45
-
-
Save giuliandrimba/4221198 to your computer and use it in GitHub Desktop.
JavaScript: namespace helper
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
function namespace(name) | |
{ | |
var namespaces = name.split("."); | |
var name = ""; | |
function getName(parent) | |
{ | |
if(namespaces.length > 0) | |
{ | |
name = namespaces.shift(); | |
if(!parent[name]) | |
{ | |
parent[name] = {} | |
} | |
return getName(parent[name], namespaces) | |
} | |
else | |
{ | |
return parent; | |
} | |
} | |
return getName(window); | |
} |
Some functional code this time:
function ns( ns, base )
{
var n, b = base || window, r = /[^\.]+/g;
while( (n = r.exec( ns ) ) != null )
b = b[n[0]] || (b[n[0]] = {});
return b;
}
Testing (at window)
ns( 'a.b.c.d.e' );
console.log( window.a );
console.log( window.a.b );
console.log( window.a.b.c );
console.log( window.a.b.c.d );
console.log( window.a.b.c.d.e );
More (custom base)
var app = {}
ns( 'a.b.c.d.e', app );
console.log( app.a );
console.log( app.a.b );
console.log( app.a.b.c );
console.log( app.a.b.c.d );
console.log( app.a.b.c.d.e );
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just some insights for a shorter version: