Skip to content

Instantly share code, notes, and snippets.

@giuliandrimba
Created December 6, 2012 01:45
Show Gist options
  • Save giuliandrimba/4221198 to your computer and use it in GitHub Desktop.
Save giuliandrimba/4221198 to your computer and use it in GitHub Desktop.
JavaScript: namespace helper
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);
}
@arboleya
Copy link

arboleya commented Jan 6, 2013

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