JavaScript namespace best practice

Written by Alexander. Posted in Uncategorized

JavaScript does not have native namespace support unlike languages like C#, Java…

But if you work in a big JavaScript project, with a lot of methods it's very difficult to work without namespaces, because avoiding namespaces in Javascript leads to name collisions. It can be collisions for functions, variables… and your code became difficult to support and extend.

But JavaScript is a very powerful programming language, and you can easy simulate namespace in Javascript with Object.

Defining namespace in JavaScript

var MyNamespace = {};
MyNamespace.sayHello = function(name)
{
   alert('Hello ' + name);
}

and you can call this code from your functions like this

function callMethod()
{
  MyNamespace.sayHello('Alexander');
}

But sometimes you require to use more than one namespace (namespace inside of namespace), it's also very easy to do with JavaScript.

var LevelOne = {};
LevelOne.LevelTwo = {};
LevelOne.LevelTwo.sayGoodbuy = function(name)
{
   alert('goodbuy ' + name);
}

And the code to call this methods

function callMethod()
{
      MyNamespace.sayHello('Alexander');
      LevelOne.LevelTwo.sayGoodbuy('Alexander');
}

Alias for namespace in JavaScript

If you have very long namespace it can be difficult to type it and require more time. But you can use simple solution with aliases.

var ns = LevelOne.LevelTwo;
ns.sayGoodbuy('Alexander');

So as you can see JavaScript namespacing is very easy and powerful.

Trackback from your site.

Leave a comment