JavaScript namespaces Part 1

Namespaces in JavaScript (JS) are necessary construct for partitioning the code in even small applications.

As ever, the key “problem” in choosing the right implementation in JavaScript is its flexibility. One has to be very disciplined and consistent in one’s thinking, so that one is never in doubt, while using JavaScript. Which itself must be a “good thing” ;) Back to namespaces now.

My first stab into the solution revolves around idea of offering to the user the possibility of sharing whatever is inside the JS namespace. Usually people want exactly the opposite. But sometimes the sharing concept is necessary.

Namespace conctruct does not exist in JS so we have to define it first. Here it is :

JS namespace is clustering of JS types and values.

Simple as that. JS types are var’s, functions, arrays and objects.  The term ‘clustering’ is used to describe a set of before mentioned types and values , which are grouped somehow using the JS language syntax and features.

The JS type used for ‘clustering’ is naturally a Function. Which in JS is kind-of-a Object which is kind-of-a Array. Why Function? We simply use the Function because the resulting JS code will look more ‘natural’ as a ‘group of JS things’ or a ‘cluster’ or a ‘namespace’. When using a Function, everything to be clustered is naturally inside the opening and closing brace. The resulting source code looks somewhat like a namespace in Java, C# or C++.

This is the concept and now, here is my first implementation of what I said above.

https://jsfiddle.net/dbjdbj/98jk1kkd/2/

Please run this code in your favourite JavaScript IDE and carefully observe the results.

DBJ