Click here to Skip to main content
15,890,557 members
Articles / Programming Languages / Javascript
Tip/Trick

Namespaces in JavaScript

Rate me:
Please Sign up or sign in to vote.
4.75/5 (18 votes)
16 Oct 2014CPOL3 min read 15K   14   1
Understanding concept of namespaces in JavaScript

Introduction

This tip describes basic information on how to use namespaces in JavaScript and their role. Why should we use namespaces and finally Aliasing Namespaces.

Understanding Namespaces in JavaScript

Namespace means bundling the different functionality under a single unique name. Like in any other language, for example, C#, we declare namespace in the following manner:

JavaScript
namespace FirstNamespace
{
  public class Demo
  {

  }
}

Now if we want to access demo class, we can call demo by explicitly calling namespace followed by class name like this:

C#
FirstNameSpace.Demo object;

But in JavaScript, concepts are different. There is no concept of namespace. By default, everything in JavaScript is global. Like if we declare 2 different functions:

JavaScript
var teacher = function(){
alert('Hi. I am Teacher');
}

var principal = function(){
alert('Hi. I am Principal');
}

These two functions are global to everyone.

What is the Disadvantage?

If any other library has these two names in common and is used after these functions, then the content of these functions will be overwritten.

What is the Solution?

Putting these two functions under one name and accessing through that variable. That's how concept of namespace comes in JavaScript.

Like:

JavaScript
var FIRSTNAMESPACE={ 
      var teacher = function(){ alert('Hi. I am Teacher'); 
                    } 
      var principal = function(){ alert('Hi. I am Principal'); 
                      }  
}

Now if you want to access your function, you simply have to write:

JavaScript
FIRSTNAMESPACE.teacher(); 

Namespaces are not finished yet. Namespaces can be nested as well. This means it is possible to make namespaces under namespaces, for example:

JavaScript
var NAMESPACE={
         ENGINEER:{
                   var engineer = function(){
                                  alert('I am Engineer');
                                  }
                  }
         DOCTOR:{
                   var doctor = function(){
                                alert('I am Doctor');
                                }
                 }
}

Now if you want to call function inside ENGINEER Namespace, then you just have to write:

JavaScript
NAMESPACE.ENGINEER.engineer();

Problem

But the problem here also continues. As the namespace is global to everyone, so any other library can easily overwrite this. So to overcome that problem, we can declare namespaces in the following manner:

JavaScript
if(typeof NAMESPACE = 'undefined'){ var NAMESPACE = {} }

or

var NAMESPACE = NAMESPACE || {}

Aliasing Namespaces

Now imagine if you have namespaces nested under other namespaces. So, it would be really hectic for user to write namespace.namespace.namespace and so on. Like:

JavaScript
var NAMESPACE={
        UNIVERSE:{
              PLANETS:{
                      EARTH:{
                             HUMANBEINGS:{
                                    var man = function(){
                                              alert('I am man.')
                                   }
                                    var woman = function(){
                                              alert('I am woman.')
                                   }
                             }
                      }
               }
        }

}

So if a developer wants to access man or woman function inside different namespaces, then he has to write:

JavaScript
NAMESPACE.UNIVERSE.PLANETS.EARTH.HUMANBEINGS.man();

or:

JavaScript
NAMESPACE.UNIVERSE.PLANETS.EARTH.HUMANBEINGS.woman();

So it would be really hectic for a developer to manage those. So to overcome this problem, JS provides us with aliasing the namespaces. So if you want to access man or woman again and again, you can keep different namespaces inside a single variable like:

JavaScript
var alias = NAMESPACE.UNIVERSE.PLANETS.EARTH.HUMANBEINGS;

and now you can call the function like this:

JavaScript
alias.man();

or:

JavaScript
alias.woman();

So it would be easy to understand and the neatness of the code is maintained.

But another disadvantage comes here. As we know, everything is global in JS, so imagine if we have a variable name and a function inside man or woman function. So a person can directly access variable name and function as well. But if we want to give access to only function name, then what do we have to do?

Can we make variable private? JS doesn't have any access modifier. So how can we restrict the variable?

Fortunately JS provides us with Modular pattern in JS, i.e., making modules.

Let's understand what module actually does and how can we make variable private.

As there is no concept of private in JS, we need to use closures to implement private variables.

Let's consider an example:

JavaScript
var NAMESPACE.DEMO.APPLICATION.method = funtion(variable){
            var variable1= variable;
            return{
                   method: function(){
                            alert('Inside Method');
                           }
                  }
}

In this code, variable1 is private and can only be used inside that method as it is inside a closure.

We can also write this code in another way. We can make both variable and function private and after that, we can show what we want to access. Like:

JavaScript
var NAMESPACE.DEMO.APPLICATION.method = funtion(variable){
            var variable1= variable;
            var method = function(){
                           alert('Inside Method');
                         }
            return{
                   method: method
                  }
}

}

In this way, we can make our method private and we can access it outside as well.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer R Systems
India India
I am working in Mindfire Solutions as Software Developer from July 2011 to present. I have experience on C#, Silverlight, Telerik Controls, Object Oriented Javascript, Jquery, Sql Server 2005, Sql Server 2008, MySQL 5.2, Backbone.js, Underscore.js, Angular.js, Bootstrap, HTML5, CSS3 .

Comments and Discussions

 
GeneralMy vote of 3 Pin
majid torfi23-Oct-14 4:21
professionalmajid torfi23-Oct-14 4:21 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.