JavaScript elegant namespace declaration

Emulating multilevel namespaces behavior in JavaScript shouldn’t be so complicated. We all know that namespacing in JavaScript is done by nesting objects. But for each nested object we have to check if it already exist so we wont overwrite it with the new object. This can happen if you write a lot of code and dynamic functional languages become harder to tame as the number of lines grows and especially JavaScript can be hard to organize and keep modular. In Python, for instance, namespace and import functionalities already exist, but not in JavaScript so we have to use tricks to emulate these behaviors.

Demo!

The trick for multilevel namespaces in JavaScript is merely an automation of the checking if the object exists so not to overwrite it, and if it doesn’t exist it nests another object by the given name from the input string. The input string is formed by names of the objects joined by a dot, for instance “ivar.util.lang”. Breaking the string by a dot we start from the root object, that is the window if no other root object is provided and we ask for existence of every of these three properties., and create them if they don’t exist.

After developing this simple method I found that YUI has almost exact system for creating namespaces in JavaScript. Be sure to check it out.

Advertisements

One comment

  1. […] / including modules in JavaScript. Combining this require module with namespace method described here provides the ultimate system for JavaScript modular […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: