Skip to content

Instantly share code, notes, and snippets.

@nzakas
Created December 6, 2011 19:14
Show Gist options
  • Save nzakas/1439504 to your computer and use it in GitHub Desktop.
Save nzakas/1439504 to your computer and use it in GitHub Desktop.
A single global with a namespace method
//BSD Licensed
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;
}
};
//usage
YourGlobal.namespace("foo.bar");
YourGlobal.foo.bar.message = "Hello world!";
YourGlobal.namespace("foo").baz = true;
@medikoo
Copy link

medikoo commented Dec 7, 2011

@nzakas I would also say that namespaces like that one are "old school" now, and using modules e.g. NodeJS style is much more worth it.
I switched to that about half year ago and don't look back.

However I wouldn't point AMD as right solution, AMD concept is ok, where you think of module as of functionality, so one module is already a quite large codebase. On programming level modules are much more fine grain and loading tens (many times hundreds) of such modules with AMD is total overkill.
I write modules Node.js style pack them for browser with modules webmake and then if I need to separate some functionalities (packs of modules) I would use some kind of loader, not sure if AMD, as it seems too big (in terms of API) for such simple needs. If someone is interested I coined better my experiences here: JavaScript Modules

@nzakas
Copy link
Author

nzakas commented Dec 7, 2011

@medikoo - I don't see modules and namespaces as mutually exclusive.

@medikoo
Copy link

medikoo commented Dec 7, 2011

@nzakas they're not, I was rather referring to style of building one big namespace (of namespaces) in one global variable, with Node.js style modules you can build complex applications and don't use global variables at all, also you don't have to nest namespaces as it's in your example.

@nzakas
Copy link
Author

nzakas commented Dec 7, 2011

@medikoo - I'm not sure why you're making so many assumptions about my intentions. Namespacing is still a useful technique, I just wanted to share this code. Use it however you want, with modules, without modules, with Node.js, with a browser...it really doesn't matter to me. This isn't a debate, it's just sharing some code.

@medikoo
Copy link

medikoo commented Dec 7, 2011

@nzakas I thought you're intention was to show new function that may help with client-side modules organization. I just wanted to shed a light on new techniques that developed recently and will be part of standard in a future (Harmony modules), that's it. If I misunderstood your point, sorry about that.

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