Skip to content

Namespace in JavaScript

In this post i would like to explain about JavaScript Namespaces. Namespaces is nothing but grouping different functionality under the single unique name.As we know in JavaScript everything is in global scope so there are high chances to overriding functions(defining functions with same name more then one time). To avoid ambiguity and minimize the risk of naming collisions we use namespaces in JavaScript.

EX: Functions in global Scope

  function test() {
    alert('test one');
  }

  function test() {
    alert('test two');
  }
 

The above two function are in global Scope ,if you call test() at the end of the file you will get alert showing “test two”. because first test function is overwritten by second test() method.

So in order to overcome this situations we put that two method in two different variables.


var NamespaceOne = {
   test : function() {
      alert('test one');
   }
}

var NamespaceTwo = {
  test : function() {
     alert('test two');
   }
}

Now if you want to access test() function , we have to write

 NamespaceOne.test();

 NamespaceTwo.test();

Using namespaces we can write code structured,readable and easy to understand JavaScript code with out polluting the global namespace.

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments