JavaScript

Namespaces in Javascript Example

If you have been previously coding in programming languages other than JavaScript, such as C# or even C++, then you might be already be familiar with the concept of namespaces and also it’s benefits in code modularity and functionality.

Unfortunately, this concept does not straight out exist in Javascript, as in they don’t have a dedicated syntax built-in the language, and every variable is added to the global scope of the application.

However, we can kind of bend this rule and work around it to create our own namespaces. How? Let’s see!
 
 

Namespaces and why we need them

Namespaces can be considered as packages of code that we use to make coding easier to fix, more efficient and understandable for whoever will maintain your website. We can use it to reduce the number of variables and functions added to our global scope, to make code modular, and so on, so they are pretty recommended. What if we don’t use them?

Since most of the times, while coding, we use external libraries or ready-made parts of code, let’s consider this to be our situation: We are putting everything in the global scope and want to add a library. The thing is, some of our variables are named the same as in the library. But they’re different things! What do we do?

Okay, let’s consider our options. We can put the library in the end of our code for the application, but the library’s code would overrule our own. And if we put it in the beginning of the code, then our code would overrule the library’s, which would make it’s use moot. Are you in favor of namespaces yet?

Syntax

Truthfully, namespaces don’t have a dedicated syntax in Javascript, so this part might be more aptly named The creation of Namespaces, but let’s just go with it. To create namespaces we would have to create a single global object and make everything else a property of that object. However, if on the way we decide we want another global object we can put it outside this object we created and it will be treated as such. The workflow follows that of other programming languages such as C++, making Javascript very similar to them.

You create a single global object like below:

var MYAPP = {
   //code here
}

After doing this, you put your whole code inside the brackets like this:

var MYAPP = {
       square: function (param) {
           return param++;
       },

       yourotherfunction: function () {
           this.title = 'Whatever you want to do with your code';
       }
}

Easy, right? So easy you feel cheated? Not my fault! Okay, okay, I will have to admit this is not really a namespace in the classical meaning of the word (Javascript’s fault), but it works as such, as you have to go through MYAPP to get to your code, and you can still use the space outside it as a global namespace.

Nested namespaces

This namespaces thing started out as copying other languages patterns on it, so let’s just do it again (all for the sake of good code!). This time it’s about nesting namespaces. We can just define an object inside the maing object we defined in the global namespace, and put a part of our code into it, like in the code snippet below:

var MYAPP = {

    FIRSTMODULE: {
           square: function (param) {
               return param++;
           }
    },
    
    SECONDMODULE: {
          yourotherfunction: function () {
               this.title = 'Whatever you want to do with your code';
           }
    }
}

You can do nesting in multiple levels to allow for better modularization, just keep in mind to not do it until you mess your code up even worse.

Namespace aliases

What if you nest your namespaces and then calling some properties of the ones in the deeper levels is a complete headache? That’s what we use aliases for. Let’s suppose we have a namespace, whose property we need to use in one of the outer levels. The code for merely accessing it would be like this:

MYAPP.FIRST.MODULE.firstproperty = function(){
       //code here
};

Imagine if you had to do operations on this property. If firstproperty = 12; and secondproperty = 1;, just to add them you will have this code in your hands:

var a = MYAPP.FIRST.MODULE.firstproperty + MYAPP.FIRST.MODULE.secondproperty;

And this would be on a best case scenario. What if you had very complicated action that you had to do with them? You give the namespace an alias like below:

var p = new MYAPP.FIRST.MODULE.firstproperty;

Now you can use only the p variable for whatever you might need. This simplifies your code considerably in case you have too much work with the innermost namespaces.

Safe namespaces

While we might be creating namespaces to avoid name collisions with libraries, we still have to give our one object a name, and exactly that name might cause the collision. To avoid it, we conduct a small check before, to make sure we’re not ruining anything. The code would go like below:

if (typeof MYAPPLICATION === "undefined") {
    var MYAPPLICATION = {};
}

This way, we only create this namespace if it’s undefined. We can even shorten this code snippet more, like below:

var MYAPP = MYAPP || {};

This way, we can rest assured that we haven’t accidentally crashed any part of our application, or even entirely.

Static Namespacing

Now that we know the basics of using namespaces we can go on to more refined and better coding practices regarding it. These best practices can be divided into two big groups: Dynamic Namespacing and Static Namespacing.

With the term “Static Namespacing” we are calling all the solutions that have a hard-coded namespace label in them (even though it might be reassigned later).

Direct assignment

Directly assigning your variables a value is the most straightforward and safe approach there is to this, as it’s very unambiguous and clear. You can do it like below:

var myApp = {}
 
myApp.param = 0;
 
myApp.next = function() {
    return myApp.param++;  
}
 
myApp.reset = function() {
    myApp.param = 0;   
}

What we’ve done here is declare a parameter in the namespace and initialize it with the value 0. We have built two functions, one of which is next() and has to increment the parameter’s value by 1, and the other is reset() which resets the parameter’s value to 0 whenever it’s invoked. If we would execute the code below we would get 0,1,2,undefined,0 as a result.

window.console && console.log(
    myApp.next(),
    myApp.next(),
    myApp.next(),
    myApp.reset(),
    myApp.next()
);

By using direct assignment we have to access the namespace whenever we want to work with a variable, and things could get really cluttered really fast. Another approach is using Object Literal Notation.

Object Literal Notation

When using the object’s literal notation we only need to reference the namespace once, and then things flow from there. This would make the code easier to maintain, but it’s no safer than directly assigning variables each time we need them. The code would go like below:

var myApp = {
 
    param: 0,
 
    next: function() {
        return this.param++;   
    }
}

Note that the usage of this, either by direct assignment or object’s literal notation is equally unsafe as it may have been re-assigned on the way. Also, while this method is better than direct assignment, it does not support logic all that much, it strictly focuses on assignment. Also it needs all the parameters to be initialized beforehand.

Module Pattern

It has been quite a lot of time since Eric Miraglia first introduced the so called Module Pattern Method, and it has since been used from many famous developers and in various important projects, and jQuery among these. This of course, for good reason. To use the Module Pattern means to wrap parts of your code in order to provide them with privacy and state throughout the course of the application in which it’s used.

The code in our case would be like in the code snippet below:

var myApp = (function() {
 
    var param= 0;
 
    return {
        next: function() {
            return param++;    
        }
    };  
})();

In this case, we have wrapped the function into brackets, as it’s one of the many ways in which the module pattern is used. While this method is really safe in that it provides privacy, it also doesn’t have the drawbacks of direct assignment and using an object’s literal notation, which makes it the better of the three. Can it get any better? It can! Let’s get on with it!

Dynamic assignment

Dynamic namespacing, or namespace injection is a method in which we represent the namespace with a proxy referenced inside the function wrapper and not out of it as usual. It makes it easier to have many independent instances of a module existing in separate namespaces, also we don’t have to scramble for a return value to assign to the namespace which makes it definition more flexible. Of course, this method supports all the perks of using module patters, and adds a lot more to it. We can put his concept to practice in two ways: By supplying with a namespace argument, or by using this as a proxy.

Giving a namespace argument

Supplying with a namespace argument can be done very simply. You just need to pass the namespace as an argument to a self-invoking function. Take a look at the example below:

var myApp = {};
(function(context) { 
    var param = 0;
 
    context.next = function() {
        return param++;    
    }
})(myApp);

Since the variable param is not directly assigned to the context, it is a private one. However, if you want it to be public you can do it with a very minor change. Instead of the namespace passed as an argument you pass this, making the code look like below:

var myApp = {};
(function(context) { 
    var param = 0;
 
    context.next = function() {
        return param++;    
    }
})(this);

The change is barely visible, but it changes a lot in the logic of your code. This is a common practice with the libraries that leave it to the user to decide whether they want specific variables to be private or not, namely used in jQuery.

this as a proxy

Using this as a proxy means to use Javascript exactly as it’s designed, without all the tricks and practices you might have gained over time. Since the namespace is injected through this, it can’t be modified without you wanting it to. Take a look at the code snippet below:

var myApp = {};
(function() {
    var param = 0;
 
    this.next = function() {
        return param++;    
    }
}).apply(myApp); 

The code doesn’t change too much from the one we used in the previous snippets, except this time we also used the method apply(), which makes it possible for the context and arguments to be separate from each other. This is quite the benefit when you want to add other arguments to the module creator, as it makes it very easy.

Moreover you can wrap your whole code and use this as a stand-in for the namespace. This way you make it easy for the maintainer of your code or user of your library to decide the context in which they wish to run the code. You can do that like below:

var name = function() {  
    //your code
}

var myApp = {};
name.apply(myApp);

Download the source code

This was an example of Namespaces in Javascript.

Download the source code for this tutorial:

Download
You can download the full source code of this example here : namespaces

Era Balliu

Era is a Telecommunications Engineering student, with a great passion for new technologies. Up until now she has been coding with HTML/CSS, Bootstrap and other front-end coding languages and frameworks, and her recent love is Angular JS.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button