Skip to content

Instantly share code, notes, and snippets.

@sysatom
Created July 31, 2014 10:02
Show Gist options
  • Save sysatom/8b1b40512b5a59477a91 to your computer and use it in GitHub Desktop.
Save sysatom/8b1b40512b5a59477a91 to your computer and use it in GitHub Desktop.
Javascript namespace
var YourGlobal = {
namespace: function(ns) {
var parts = ns.split("."),
object = this,
i, len;
for(i = 0, len=parts.length; i < len; i++) {
if(!object[parts[i]]){
object[parts[i]] = {};
}
object = object[parts[i]];
}
return object;
}
};
// Example
YourGlobal.namespace("Books.AboutJavascript");
YourGlobal.Books.AboutJavascript.author = "xxx";
YourGlobal.namespace("Books.OtherJavascript");
console.log(YourGlobal.Books.AboutJavascript.author);
YourGlobal.namespace("Books").ANewBook = {};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment