JavaScript tip 3: Namespaces

To avoid collisions, declarations overwriting each other and such, we can use JavaScript to create namespaces.

While not supported directly by the language the pattern is pretty common.

First let’s imagine we are including two separate JS files which both include a function named customRounding.

// first included file
var customRounding = function(number) {
  return number.toFixed(2);
}

// second included file
var customRounding = function(num) {
  return num.toFixed(3);
}

In our index.html we are calling this function:

console.log(customRounding(1.23456));

The problem is that the second file will have overwritten the declaration in the first file. To prevent such a collision, it is advisable to use a namespace likewise:

// first included file
var NS1 = {
  customRounding: function(number) {
    return number.toFixed(2);
  }
};

// second included file
var NS2 = {
  customRounding: function(num) {
    return num.toFixed(3);
  }  
};

// in our index.html file
console.log(NS1.customRounding(1.23456));

We can also use this pattern to make some variables and functions private by converting our namespace to an IIFE and then declaring the private members as variables and returning our public members:

var NS1 = (function() {
  // private stuff
  var aPrivateVar = 42;
  var aPrivateFunction = function(number) {
    alert('Hi!');
  };

  // public stuff
  return  {
    customRounding: function(number) {
      return number.toFixed(2);
    }  
  };  
})();

 

 

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