Is there a “concise” way to do namespacing in JavaScript?
-
08-06-2019 - |
Question
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.]
Solution
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:
var namespaces = { com: { example: { /* example.com's data */ } } }
This is a variable namespaces
being 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.
var com_example_data = { /* example.com's data */ };
That works just as well, without the pointless hierarchy.
Now, if you actually want to build a hierarchy, you can try something like this:
com_example = com_example || {};
com_example.flags = com_example.flags || { active: false, restricted: true};
com_example.ops = com_example.ops || (function()
{
var launchCodes = "38925491753824"; // hidden / private
return {
activate: function() { /* ... */ },
destroyTheWorld: function() { /* ... */ }
};
})();
...which is, IMHO, reasonably concise.
OTHER TIPS
Here was an interesting article by Peter Michaux on Javascript Namespacing. He discusses 3 different types of Javascript namespacing:
- Prefix Namespacing
- Single Object Namespacing
- Nested Object Namespacing
I won't plagiarize what he said here but I think his article is very informative.
Peter even went so far as to point out that there are performance considerations with some of them. I think this topic would be interesting to talk about considering that the new ECMAScript Harmony plans have dropped the 4.0 plans for namespacing and packaging.
I try to follow the Yahoo convention of making a single parent object out in the global scope to contain everything;
var FP = {};
FP.module = {};
FP.module.property = 'foo';
To make sure you don't overwrite an existing object, you should so something like:
if(!window.NameSpace) {
NameSpace = {};
}
or
var NameSpace = window.NameSpace || {};
This way you can put this at the top of every file in your application/website without worrying about the overwriting the namespace object. Also, this would enable you to write unit tests for each file individually.
The YUI library library has code which handles namespacing using a function which you may find preferable. Other libraries may do this also.
As an alternative to a dot or an underscore, you could use the dollar sign character:
var namespaces$com$example = "data";
I like also this (source):
(function() {
var a = 'Invisible outside of anonymous function';
function invisibleOutside() {
}
function visibleOutside() {
}
window.visibleOutside = visibleOutside;
var html = '--INSIDE Anonymous--';
html += '<br/> typeof invisibleOutside: ' + typeof invisibleOutside;
html += '<br/> typeof visibleOutside: ' + typeof visibleOutside;
contentDiv.innerHTML = html + '<br/><br/>';
})();
var html = '--OUTSIDE Anonymous--';
html += '<br/> typeof invisibleOutside: ' + typeof invisibleOutside;
html += '<br/> typeof visibleOutside: ' + typeof visibleOutside;
contentDiv.innerHTML += html + '<br/>';
Use an object literal and either the this
object or the explicit name to do namespacing based on the sibling properties of the local variable which contains the function. For example:
var foo = { bar: function(){return this.name; }, name: "rodimus" }
var baz = { bar: function(){return this.name; }, name: "optimus" }
console.log(foo.bar());
console.log(baz.bar());
Or without the explicit name
property:
var foo = { bar: function rodimus(){return this; } }
var baz = { bar: function optimus(){return this; } }
console.log(foo.bar.name);
console.log(baz.bar.name);
Or without using this
:
var foo = { bar: function rodimus(){return rodimus; } }
var baz = { bar: function optimus(){return optimus; } }
console.log(foo.bar.name);
console.log(baz.bar.name);
Use the RegExp
or Object
constructor functions to add name properties to counter variables and other common names, then use a hasOwnProperty
test to do checking:
var foo = RegExp(/bar/);
/* Add property */
foo.name = "alpha";
document.body.innerHTML = String("<pre>" + ["name", "value", "namespace"] + "</pre>").replace(/,/g, "	");
/* Check type */
if (foo.hasOwnProperty("name"))
{
document.body.innerHTML += String("<pre>" + ["foo", String(foo.exec(foo)), foo.name] + "</pre>").replace(/,/g, "	");
}
/* Fallback to atomic value */
else
{
foo = "baz";
}
var counter = Object(1);
/* Add property */
counter.name = "beta";
if (counter.hasOwnProperty("name"))
{
document.body.innerHTML += String("<pre>" + ["counter", Number(counter), counter.name] + "</pre>").replace(/,/g, "	");
}
else
{
/* Fallback to atomic value */
counter = 0;
}
The DOM uses the following convention to namespace HTML and SVG Element interface definitions:
- HTMLTitleElement
- SVGTitleElement
- SVGScriptElement
- HTMLScriptElement
JavaScript core uses prototypes to namespace the toString
method as a simple form of polymorphism.
References
- Does javascript autobox?
- Getting sibling value of key in a JavaScript object literal
- MDN: JavaScript Operators - this as an object method
- Lua: technical note 7 - Modules and Packages
- HTMLTitleElement.webidl
- SVGTitleElement.webidl
- SVGScriptElement.webidl
- HTMLScriptElement.webidl
- The names of functions in ES6
- ECMAScript 2015 Language Specification - 19.2.4.2 Function Instances: name | ECMA-262 6th Edition