jQuery Function Namespacing in Plain English

jquery-namespacing

Namespacing is a must know for any JavaScript developer especially when your learning the basics, it’s essential you form a solid basis and know how to protect your code. I think a good way to start this off is by explaining what is is and giving you some examples of namespacing in JavaScript/jQuery.

What is namespacing?

In a nutshell, namespacing is a way to protect your code using javascript object literal notation to provide encapsulation. Minimizing your code’s footprint in this root scope by structuring your methods/data inside a single namespace should be the goal of every decent developer. The advantages are that you can name your variables whatever you like and not have to worry about some other code overwriting it’s value. In this post I’m going to show you nested object namespacing because this is the most common form of namespacing in jQuery.

Ok, lets dive straight into some examples.

You can paste any of these examples straight into the Firebug console to see what it does and play around with it.

This is a regular way to declare a function in JavaScript.

myFunction = function()
{
    console.log('running myFunction...');
};
myFunction(); //function call

Now the problem with this, is any other code could also declare a function call “myFunction” and this would overwrite yours! Not good. So what’s the solution? You guessed it, namespacing!

A basic namespace

Here is how you would create a basic namespace to protect your function:

;MYNAMESPACE = {

    myFunction: function()
    {
        console.log('running MYNAMESPACE.myFunction...');
    }
   
}
MYNAMESPACE.myFunction(); //function call

Now, nothing can overwrite your function and everything is contained within a namespace called “MYNAMESPACE”. To call your function you simply include the namespace before the function.

Naming your space

Ok, so you have looked at the code above and wondered why the namespace is all capitals. It’s my preference to keep namespaces in capitals because they are JavaScript referenced objects, but this depends on your personal or work coding practices. It’s also a good to keep them short as possible so I probably should have called my namespace “NS” or such (This is because namespaces can get long when chained together, we’ll go through this later on in the post).

A namespace with multiple functions

You can also declare variables and more functions, as many as you like. All of which are “local” to that namespace (it sort of acts like a controller to that code). Just remember the syntax changes within namespaces because you are referencing an object literal so you need to add commas after each statement instead of semi-colons.

;MYNAMESPACE = {

    name: 'MYNAMESPACE',

    myFunction1: function()
    {
        console.log('running MYNAMESPACE.myFunction...');
    },
    myFunction2: function()
    {
        console.log('running MYNAMESPACE.myFunction...');
    }
   
}
console.log(MYNAMESPACE.name); //variable call
MYNAMESPACE.myFunction1(); //function call
MYNAMESPACE.myFunction1(); //function call

A namespaces inside a namespace

Now your thinking what about a namespace inside a namespace, sort of a sub-namespace. Yes, this is also possible you would just need to make sure your main namespace is declared beforehand, like this:

;var MYNAMESPACE = {};
MYNAMESPACE.SUBNAME = {

    myFunction: function()
    {
        console.log('running MYNAMESPACE.SUBNAME.myFunction...');
    }
   
}
MYNAMESPACE.SUBNAME.myFunction(); //function call

A self encapsulated jQuery namespace structure

Ok, now suppose you wanted to use a self encapsulated jQuery function (also known as an “anonymous function“, or “self executing function”) to wrap around your namespace but you want to be able to reference your objects, functions and variables held within.

Firstly, you would need to declare the namespace outside the enclosing function to make the object assessable from outside, like so:

;var MYNAMESPACE = {};

If you don’t create the variable in the outer scope you will surely see the following error: ‘ReferenceError: MYNAMESPACE is not defined’.

This is the full structure of the code which has full encapsulation using namespacing and includes the dollar sign ($) for use with jQuery code only inside the enclosed jQuery function to prevent naming conflicts with other frameworks.

;var MYNAMESPACE = {};
;(function($) {

    MYNAMESPACE.SUBNAME = {
        myFunction: function()
        {
            console.log('running MYNAMESPACE.SUBNAME.myFunction...');
        }
    }
   
})(jQuery);
MYNAMESPACE.SUBNAME.myFunction(); //function call

Using the window scope alternative

Passing through parameters to anonymous functions, like jQuery – is awesome because in your case its lets you use $ even if jQuery.noConflict() is set. So in that sense it would make perfect sense if your code in your namespace used ‘$’.

You could actually still stick all the code inside the self executing function by just assigning MYNAMESPACE to the window scope (same effect as using var in the global scope above). Then you have your encapsulation and you’re free to use $.

;(function($) {
    // declare var in global scope
    window.MYNAMESPACE = {};

    MYNAMESPACE.SUBNAME = {
        myFunction: function()
        {
            console.log('running MYNAMESPACE.SUBNAME.myFunction...');
        }
    }
 
})(jQuery);
MYNAMESPACE.SUBNAME.myFunction(); //function call

That’s it! I hope you learnt something about namespacing in JavaScript/jQuery. If not, please feel free to leave a comment. Next post, i’ll look into event namespacing, which is awesome.