jQuery Function Namespacing in Plain English

Sam Deering

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.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • Dan

    Hey man,
    Good post.

    You nailed it – namespacing is 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.

    Only terminology but I notice what you are calling a self encapsulated jQuery function, I have heard of being called an “anonymous function”, or “self executing function”, but technically they’re not tied to jQuery in anyway. One of the purposes of using anonymous functions is to create a new scope (every function has its own scope), so in a way they can also provide encapsulation of code which in your specific example is a little redundant.

    However 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 as you have).

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

    MYNAMESPACE.SUBNAME = {
    myFunction: function()
    {
    console.log(‘running MYNAMESPACE.SUBNAME.myFunction…’);
    }
    }

    })(jQuery);
    MYNAMESPACE.SUBNAME.myFunction(); //function call
    Then you have your encapsulation and you’re free to use $.

    Love the blog by the way.

    Dan

  • Pingback: 10 jQuery Developer Tips to Improve you | Developers Blog

  • http://1stwebdesigner.com Rochester

    A.M.A.Z.I.N.G.

    Great post, thanks!
    []’s

  • Pingback: 5 Different Ways to Declare Functions in jQuery | jQuery4u

  • Pingback: 5 jQuery.each() Function Examples | jQuery4u

  • Tameshwar

    Awesome……

  • Pingback: jQuery output array in random order | jQuery4u

  • Pingback: The Fascade JavaScript Design Pattern | jQuery4u

  • Pingback: A Basic jQuery Plugin using the Module Pattern | jQuery4u

  • http://about.me/mikeschinkel Mike Schinkel

    Nice article. However, I’ve never seen code prefixed with a semi-colon at the beginning of a line; why do you do that?

    • jquery4u

      @Mike, it’s there because it you have a python script (or such) to combine your .js files and compress for include it prevents any scripts breaking that may have omitted an ending semi colon. Other than that it’s not really needed, but won’t ever break your script.

  • Pingback: BizSugar.com

  • Harold

    Thanks for this explanation! There are a ton of posts and tutorials about this, but this really made me understand it properly.

    • http://jquery4u.com/ jQuery4u

      Thanks Harold

  • Marinda

    Thanks alot! Have an exam tomorrow and this was the part i was not looking forward to studying. But now you managed to make me understand it in 10 minutes! :)

  • domo

    nice tut , nice site, keep them coming

  • Guest

    Nice article.

  • http://ramesh-vishwakarma.com Ramesh Vishwakarma

    Great article… I love this blog.

  • http://quaverlovestudio.net/ Simon @ QLS

    Really great post, indeed! I’ve learned a lot, here… including how to overcome the jQuery.noConflict() issue, something I battled with for a while, then gave up… perfect!