I’ve frequently encountered sites that put all of their JavaScript inside a namespace structure along the lines of:
namespaces = { com : { example: { example.com's data} }
However, setting this up safely with respect to other namespaced frameworks seems to require a relatively hefty amount of code (defined as > 2 lines). I was wondering whether anyone knows of a concise way to do this? Furthermore, whether there’s a relatively standard/consistent way to structure it? For example, is the com namespace directly attached to the global object, or is it attached through a namespace object?
[Edit: whoops, obviously {com = { ... } } wouldn’t accomplish anything close to what I intended, thanks to Shog9 for pointing that out.]
Javascript doesn’t have stand-alone namespaces. It has functions, which can provide scope for resolving names, and objects, which can contribute to the named data accessible in a given scope.
Here’s your example, corrected:
This is a variable
namespacesbeing assigned an object literal. The object contains one property:com, an object with one property:example, an object which presumably would contain something interesting.So, you can type something like namespaces.com.example.somePropertyOrFunctionOnExample and it’ll all work. Of course, it’s also ridiculous. You don’t have a hierarchical namespace, you have an object containing an object containing an object with the stuff you actually care about.
That works just as well, without the pointless hierarchy.
Now, if you actually want to build a hierarchy, you can try something like this:
…which is, IMHO, reasonably concise.