Advanced Namespacing Patterns
We’ll now explore some advanced patterns and utilities that I have found invaluable when working on larger applications, some of which have required a rethink of traditional approaches to application namespacing. I’ll note that I am not advocating any of the following as the way to namespace, but rather ways that I have found work in practice.
Automating Nested Namespacing
As we’ve reviewed, nested namespaces can provide an
organized hierarchy of structure for a unit of code. An example of such
a namespace could be the following:
application.utilities.drawing.canvas.2d. This
can also be expanded using the object literal pattern to be:
varapplication={utilities:{drawing:{canvas:{2d:{//...}}}}};
One of the obvious challenges with this pattern is that each additional layer we wish to create requires yet another object to be defined as a child of some parent in our top-level namespace. This can become particularly laborious when multiple depths are required as our application increases in complexity.
How can this problem be better solved? In JavaScript Patterns, Stoyan Stefanov presents a very clever approach for automatically defining nested namespaces under an existing global variable. He suggests a convenience method that takes a single string argument for a nest, parses this, and automatically populates our base namespace with the objects required.
The method he suggests using is the following, which I’ve updated it to be a generic function for ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access