Skip to content

Instantly share code, notes, and snippets.

@leecade
Forked from 140bytes/LICENSE.txt
Created October 8, 2011 14:21
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 leecade/1272345 to your computer and use it in GitHub Desktop.
Save leecade/1272345 to your computer and use it in GitHub Desktop.
namespace

namespace

//"window" //"window.a" //"a" //"a.b.c" //any custom context

function (a,b,c,d){c=a.replace(/^window.?/,"").split("."),b=b||window;while(d=c.shift())b=b[d]=b[d]||{};return b}
function(
a, //input string
b, //context
c, //(placeholder)
d //(placeholder)
){
c = a.replace(/^window.?/, '').split('.'); //replace ^window and split
b = b || window; //default context
while(d = c.shift()) b = b[d] = b[d] || {};
return b;
}
{
"name": "namespace",
"description": "namespace",
"keywords": [
"namespace",
"javascript",
"斯人",
"leecade"
]
}
@atk
Copy link

atk commented Oct 10, 2011

How about using the replace for the loop?

function (a,b){b=b||window;a.replace(/^window\.|([^\.]+)/g,function(c,d){b=d?b[d]||{}:b});return b}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment