Namespacing in JavaScript

Global variables should be reserved for objects that have system-wide relevance and they should be named to avoid ambiguity and minimize the risk of naming collisions. In practice this means you should avoid creating global objects unless they are absolutely necessary.

But, hey, you already knew all that…..

So what do you do about it? Conventional wisdom tells us that the best global abatement strategy is to create a small number of global objects which will serve as de facto namespaces for underlying modules and subsystems. I’m going to explore several approaches to namespacing, culminating in an elegant, safe and flexible solution that I based on a recent article by James Edwards.

Static Namespacing

I’m using static namespacing as an umbrella term for solutions in which the namespace label is effectively hard coded. It’s true, you could re-assign one namespace to another but the new namespace will reference the same objects as the old one.

1. By Direct Assignment

The most basic approach. Its verbose and if you ever wanted to rename the namespace you’ve got a job on your hands. However its safe and unambiguous.

var myApp = {}

myApp.id = 0;

myApp.next = function() {
	return myApp.id++; 	
}

myApp.reset = function() {
	myApp.id = 0; 	
}

window.console && console.log(
	myApp.next(),
	myApp.next(),
	myApp.reset(),
	myApp.next()
); //0, 1, undefined, 0	

 
You could make future maintenance a little easier by using this to reference sibling properties – but this is a little risky since there is nothing to stop your namespaced functions from being reassigned:

var myApp = {}

myApp.id = 0;

myApp.next = function() {
	return this.id++; 	
}

myApp.reset = function() {
	this.id = 0; 	
}

myApp.next(); //0
myApp.next(); //1
var getNextId = myApp.next;
getNextId(); //NaN whoops!

 
2. Using Object Literal Notation

Now we need only refer to the namespace name once, so switching the name later is a little easier (assuming you haven’t already referenced the namespace too often). There is still a danger that the value of this might throw a surprise – but its a little safer to assume that objects defined within an object literal construct will not be reassigned.

var myApp = {

	id: 0,

	next: function() {
		return this.id++; 	
	},

	reset: function() {
		this.id = 0; 	
	}
}
window.console && console.log(
	myApp.next(),
	myApp.next(),
	myApp.reset(),
	myApp.next()
) //0, 1, undefined, 0

 
3. The Module Pattern

I find myself using the module pattern more often these days. The logic is shielded from the global scope by a function wrapper (usually self-invoking) which returns an object representing the module’s public interface. By immediately invoking the function and assigning the result to a namespace variable, we lock up the module’s API in the namespace. Additionally any variables not included in the return value will remain forever private, visible only to the public functions that reference them.

var myApp = (function() {

	var id= 0;

	return {
		next: function() {
			return id++; 	
		},

		reset: function() {
			id = 0; 	
		}
	};	
})();	

window.console && console.log(
	myApp.next(),
	myApp.next(),
	myApp.reset(),
	myApp.next()
) //0, 1, undefined, 0	

 
Like the object literal example above, the receiving namespace can be easily switched, but there are added advantages: object literal notation is rigid – its all about property assignments, with no room for supporting logic. Moreover all properties must be initialized and property values cannot easily cross reference one another (so, for example, internal closures are not possible). The module pattern suffers none of these constraints and gives us the added benefit of privacy.

Dynamic Namespacing

We could also call this section namespace injection. The namespace is represented by a proxy which is directly referenced inside the function wrapper – which means we no longer have to bundle up a return value to assign to the namespace. This makes namespace definition more flexible and makes it very easy to have multiple independent instances of a module existing in separate namespaces (or even in the global context). Dynamic namespacing supports all the features of the module pattern with the added advantage of being intuitive and readable.

4. Supply a Namespace Argument

Here we simply pass the namespace as an argument to a self-invoking function. The id variable is private because it does not get assigned to the context.

var myApp = {};
(function(context) { 
	var id = 0;

	context.next = function() {
		return id++; 	
	};

	context.reset = function() {
		id = 0; 	
	}
})(myApp);	

window.console && console.log(
	myApp.next(),
	myApp.next(),
	myApp.reset(),
	myApp.next()
) //0, 1, undefined, 0	

 
We can even set the context to the global object (with a one word change!). This is a big asset for library vendors – who can wrap their features in a self-invoking function and leave it to the user to decide whether they should be global or not (John Resig was an early adopter of this concept when he wrote JQuery)

var myApp = {};
(function(context) { 
	var id = 0;

	context.next = function() {
		return id++; 	
	};

	context.reset = function() {
		id = 0; 	
	}
})(this);	

window.console && console.log(
	next(),
	next(),
	reset(),
	next()
) //0, 1, undefined, 0	

 
5. Use this as a Namespace Proxy

A recent posting by James Edwards piqued my interest. My Favorite JavaScript Design Pattern was apparently misunderstood by many commentators, who thought he might as well resort to the module pattern. The article peddles multiple techniques (which probably contributed to readers’ confusion) but at its heart is a little bit of genius which I’ve revamped and presented a namespacing tool.

The beauty of the pattern is that it simply uses the language as designed – nothing more, nothing less, no tricks, no sugar. Moreover because the namespace is injected via the this keyword (which is static within a given execution context) it cannot be accidentally modified.

var myApp = {};
(function() {
	var id = 0;

	this.next = function() {
		return id++; 	
	};

	this.reset = function() {
		id = 0; 	
	}
}).apply(myApp);	

window.console && console.log(
	myApp.next(),
	myApp.next(),
	myApp.reset(),
	myApp.next()
); //0, 1, undefined, 0

 
Even better, the apply (and call) APIs provide natural separation of context and arguments – so passing additional arguments to the module creator is very clean. The following example demonstrates this, and also shows how to run the module independently over multiple namespaces:

var subsys1 = {}, subsys2 = {};
var nextIdMod = function(startId) {
	var id = startId || 0;

	this.next = function() {
		return id++; 	
	};

	this.reset = function() {
		id = 0; 	
	}
};

nextIdMod.call(subsys1);	
nextIdMod.call(subsys2,1000);	

window.console && console.log(
	subsys1.next(),
	subsys1.next(),
	subsys2.next(),
	subsys1.reset(),
	subsys2.next(),
	subsys1.next()
) //0, 1, 1000, undefined, 1001, 0

 
Of course if we wanted a global id generator, its a breeze…

nextIdMod();    

window.console && console.log(
    next(),
    next(),
    reset(),
    next()
) //0, 1, undefined, 0

 
The id generator tool we’ve been using as an example does not do justice to the full potential of this pattern. By wrapping an entire library and using the this keyword as a stand in for the namespace we make it easy for the user to run the library in whichever context they choose (including the global context)

//library code
var protoQueryMooJo = function() {	
	//everything
}

//user code
var thirdParty = {};
protoQueryMooJo.apply(thirdParty);

 

Other considerations

I try to avoid nested namespaces. They are harder to follow (for both human and computer) and they will bulk out your code with cruft. As Peter Michaux points out, deeply nested namespaces may be a legacy of nostalgic Java developers trying to recreate the lengthy package chains they knew and loved.

It’s possible to span a single namespace across .js files (though only by namespace injection or direct assignment of every variable) however you should be careful with dependencies. Moreover binding a namespace to a file can help the reader more easily navigate the codeline.

Since JavaScript has no formal namespace construct, there is a rich landscape of home grown solutions out there. This survey details just a few of them and there may well be better techniques that I did not cover. I’d love to hear about them.

Further reading

James Edwards: My Favorite JavaScript Design Pattern
Peter Michaux: JavaScript Namespacing

About these ads

78 thoughts on “Namespacing in JavaScript

  1. Pingback: Tweets that mention Namespacing in JavaScript | JavaScript, JavaScript -- Topsy.com

  2. I like the concept of 5, but when you need access to both the ‘this’ object and, for example, the ‘this’ in the context of a click callback, you have to assign the outer context ‘this’ to another variable anyway. At that point, you’re starting to confuse which ‘this’ is which.

    I like 4 because it removes one more level of ‘this’.

      • @Will @Dan

        Hi guys – yes ‘this’ pollution can be an issue in itself – however in this case I’m not sure I see a problem….

        Each function call gets its own ‘this’ property. Since the wrapper function was only created to isolate the namespace context it is designed to be called just once. A click callback, for example will be defined in an inner function and will therefore have its own ‘this’ context.

        Moreover if you want the global context there are normally other ways to reference it (e.g. window in the case of browser code) – or better still, pass it as an argument to your function wrapper

        (function(global) { 
            global.blah(); 
            //more code
        }).call(myApp, this)
        
      • Yeah, Angus, I get that, but the following gets messy:

        var myApp = {};
        (function() {
            this.id = 1;
            this.myHandler = function(){
                alert(this.id); //should alert the clicked dom element's id
            };
            $('a').click(this.myHandler);
        }).apply(myApp);
        
      • Will, you’re going all JQuery on me now ;-)
        I’m not a JQuery expert but I’m not sure why your example will not work. JQuery’s click will bind $(a) to this.myHandler – so $(a) becomes the myHandler function’s ‘this’

        Or are you just saying this makes the code look uglier?

      • I’m not even a jQuery guy, just figured I’d keep the code simplistic. :)

        It definitely works, I was just commenting on how that gets a little confusing. Not insurmountable, and you’d even with #4 get into the ‘this’ problem, but I think #5 is just making it messier. Mine is merely a subjective comment.

        I think #5 is cool and clean in theory and I don’t mean to knock it, I just think it’ll get messy faster.

      • The this will always refer to the innermost this availible, eg the one sent from clickhandler or whatever.
        A common hack to use other this’es is to redefine this to a local variable. It seems to be a convention that people use “that” as variablename.

        function NS() {
        var that= this; //Storing our desired "this"
        this.doSomething= function(){
        that.foo(); //use "that" to reference the outer "this"
        };
        this.foo = function(){};
        setTimeout(this.doSomething, 100); //here "this" is still withing the scope but using "that" would have worked aswell.
        }
        var myNS = new NS();
        var a = myNs.doSomething;
        a(); //will still work

  3. Pingback: Namespacing in JavaScript | JavaScript, JavaScript « Netcrema – creme de la social news via digg + delicious + stumpleupon + reddit

  4. In #5, call should probably be used instead of apply since you’re not passing any arguments and you know you’re not passing any arguments. Call is a bit faster on most platforms if you know your argument list. There is a test for it on jsperf if you want to see. If performance isn’t your cup of tea, call is one less character to type and send down the wire ;).

    • Hi Bryan – since its only likely to be invoked a few times at most its not a major issue for this pattern. But interesting point anyway – I wasn’t aware of the performance difference.

  5. Pingback: Namespacing in JavaScript | JavaScript, JavaScript » Web Coding Unravelled

  6. Pingback: HTML all you need to know» Blog Archive » Namespacing in JavaScript | JavaScript, JavaScript

  7. Thanks again for this writing this article. The two links to “JavaScript Namespacing” article are malformed ;)

  8. Pingback: Namespacing in JavaScript | JavaScript, JavaScript – javascript - dowiedz się więcej!

  9. Hello.
    I am absolutely newbie in Javascript, and this is the first article I read about design patterns in JS.
    My question is:
    which debugger will manage those (quite complicated) constructs?
    Let’s say I want to put a breakpoint at code “return id++”, will a debugger really stop at that line in each of the presented cases?

    • Yes – any debugger will stop at any line. Firefox’s firebug add-on is probably still the best, but the webkit browsers (chrome and safari) have nice debuggers in their built in developer tool. IE8/9 also has a built in debugger

      You can also type ‘debugger’ in your sourcecode before any line you want to stop at

  10. I have a different solution: http://jweir.github.com/namespace/

    It is a modular approach, inspired by Erlang. The syntax is very clean and gives you private/public methods.

    (function(){
        // a string for the namespace, and the functions to make public
        namespace("book", create, update);
    
        function private(title){
            return {title:title, author:"Bill"};
        } 
    
        function create(title){  
            return private(title);
        };
    
        function update(){ 
            //...
        };
    })();
    
    book.create("Whitepages");
    

    It accepts nested namespaces, an automatically generates any parents if they don’t exist.

    namespace("book.author", ...functions to export...);

  11. Pingback: Namespacing in Javascript | subtly simple

  12. I take a slightly different approach to how I create namespaces, I’ve got a piece of code which I keep in my toolbox which has a function on it for creating namespaces, allowing you to do this:

    slace.core.registerNamespace(‘some.new.namespace’);

    It’ll also ensure that if you’ve already got a ‘some’ object (or a ‘some’ object with a ‘new’ property) then they’ll just get appended down the chain.

    Code (and explanatory blog) can be found here.
    One other nifty feature of the method I use is that you can augment existing objects too:

    var foo = { bah: ‘bah’ };
    slace.core.registerNamespace(‘anotherBah’, foo);

    Now ‘foo’ looks like:

    {
    bah: ‘bah’,
    anotherBah: { }
    }

  13. Pingback: JavaScript Magazine Blog for JSMag » Blog Archive » News roundup: Crankshaft, WebSockets disabled, 3d Christmas tree

  14. Pingback: BenjaminKeen.com

  15. Don’t forget the CommonJS module pattern, which is used in node.js and can be conveniently used in the browser using Transporter, RequireJS or a number of other loaders.

    Here’s the basic pattern (adjusted for using in the browser with RequireJS):


    define(function(require, exports, module) {
    var mathlib = require("mathlib");

    exports.computeFoo = function(x) {
    return mathlib.someComplexThing(x) * mathlib.somethingElse(x);
    };
    });

    CommonJS modules are a nice stepping stone for the proposed ECMAScript Harmony modules:

    http://wiki.ecmascript.org/doku.php?id=strawman:simple_modules

    though they clearly can’t do everything Harmony modules can do because that’s why they’re adding modules to the language :)

    Kevin

  16. Pingback: ITXMedia | Great Readings for those Web Developers out there.

  17. Pingback: links for 2010-12-13 « BarelyBlogging

  18. Pingback: Javascript: Orienté objet et manipulation du prototype (via call/apply) « MKLog.fr

  19. Pingback: 網站製作學習誌 » [Web] 連結分享

  20. Pingback: The Morning Brew - Chris Alcock » The Morning Brew #760

  21. Pingback: Tweets that mention Namespacing in JavaScript | JavaScript, JavaScript -- Topsy.com

  22. Pingback: Friday Links #133 | Blue Onion Software *

  23. Pingback: Rounded Corners 266 — Graceless Degradation /by @assaf

  24. #4 and #5 are nice and I like using call / apply, but to get the benefit of multiple namespaces (subsys1 / subsys2) you’ll have an additional variable hanging around (nextIdMod) which is not so clean if the reason you are using it is to namespace.

    In cases where additional instances are necessary they are usually not a large library and you can just use the traditional “new” on a function to construct a PlainOldJavaScriptObject.

    I like the revealing module pattern in that it has immediate invocation (no additional variable) no this / that issue, no implementation in the return object, clean anon object return names (chance to relabel), and probably is less memory intensive because it doesn’t need to keep around anything like (nextIdMod).

    http://www.wait-till-i.com/2007/08/22/again-with-the-module-pattern-reveal-something-to-the-world/

  25. Pingback: Namespacing en Javascript | Web.Ontuts

  26. Pingback: URL Design, JavaScript Namespaces, & More | Tom McFarlin

  27. Hi Angus,

    Nice summary of options!

    Apart from namespacing you also have the related issues of isolation and versioning; In one case you may have two pieces of code using a function or object with the same name. You want to isolate these pieces of code and the functions/objects they use from each other so they don’t collide. Versioning is the same principle, but here the functions with the same name are basically two versions of the same code, where one piece of code is using the old version when an other piece of code wants to use the new version.

    This also brings up the subject of dependency management. Wouldn’t it be great if you could have one piece of code declare it’s dependence on another piece of code and have those dependencies be automatically resolved?

    I have spent quite some time on this subject and came up with a solution that not only handles the name spacing part, but also takes care of isolation with an ‘import’ mechanism where the dependencies for a module (called Packages in my code) are automatically resolved and imported objects injected into the namespace as arguments to the very function that forms the body of the package:

    Package("hello", [], function() {
      function greeting() {
        alert("Hello World!")
      }
    });
    
    Package("example", ["hello"], function(greeting) {
      // You can use greeting here, it is injected automatically
      greeting();  // Alerts: "Hello World!"
    });
    

    Both packages would be in separate files with the names following a convention (package name + .js) so the framework can automatically include them.

    Check it out, i’m really curious what you think about it!
    Packages JS

    -Stijn

  28. Argh, shouldn’t type code by heart! In the previous example I forgot one statement in the package “hello”:

    Package("hello", [], function() {
      function greeting() {
        alert("Hello World!")
      }
      // Make greeting available to other packages
      Export("greeting", greeting); 
    });
    

    My site includes actual working examples, not the buggy stuff posted by heart. :)

    • Hi Stijn

      Sorry I’ve been very busy (just started new job and submitting a new blog tomorrow!) so have had very little time to look at Packages. However I had a quick scan of the source code and the tidiness appeals to me. I’ll let you know more when I have a chance to look properly

      Angus

  29. Thanks Angus. I have been working on a new version and it’s a bit cleaner still than the one that is there currently, I hope to be able to put it up this week. I will let you know once it’s there (saves you looking into the old version :) )

  30. Pingback: Keep Javascript Libraries From Colliding

  31. Thanks for this article, Angus!

    Super small comment: there’s a missing semi-colon in the example for #5, after apply().

  32. Hi,

    Clicking on the ‘copy’ button on code blocks is not copying anything to clipboard.

    Here I use Chrome (10.0.648.204) on Maverick.

    Thanks!

  33. Pingback: JQuery Trainer | Gioorgi.com

  34. Pingback: 命名空间 (namespace) – JavaScript | Redky

  35. Great article, I learnt a lot.

    A question re. #5 – what would happen if the function wrapper returned the this? object? Could you write like this?

    var myApp = (function() {
    this.a = ‘a';
    return this;
    }).apply({});

    var myApp = (function() {
    this.b = ‘b';
    return this;
    }).apply(myApp || {});

  36. Pingback: Dynamics CRM Forms and Object Oriented Javascript | Business Technology Blog

  37. That’s how most of my js files look like:

    (function () {

    var Long = my.namespace.can.be.Long = function () {};

    Long.prototype.myMethod = function () {};

    (function () {
    var privateVariable = 3;
    Long.prototype.myOtherMethodThatUsesManyPrivateVariables = function () {};
    })();

    })();

  38. Pingback: Namespaces in CoffeeScript « D^t on Code

  39. Pingback: Essential jQuery Plugin Patterns - blog.topwebdevelop.com

  40. Pingback: Essential jQuery Plugin Patterns | Top website Designing Company in India

  41. Pingback: Helpful Links Every Developer Should Have | The PHP Coder's Judy Chop

  42. All of these namespacing examples result in an object of nested objects, ie a Matrioshka/babushka hierarchy.

    What if you want to adjust a name on one of the child objects in the future without breaking relationanal connections?
    What if you want to improve performance by reducing the look up between ‘parent’ and ‘parent.child.subchild’?

    I propose a cleaner solution as suggested by an old article on using underscores to namespace.

    http://michaux.ca/articles/javascript-namespacing

    1) Store a module in a singleton object or class if you prefer.
    2) Store all children and childrens’ children on one level of your module.
    Example:
    var myModule = {
    ‘parent':doWhatever:function(){
    //myModule['parent.child.subchild']();
    //OR
    //this['parent.child.subchild']();
    },
    ‘parent.child':function(){
    },
    ‘parent.child.subchild':function(){
    }
    }
    This is much easier to read. The dot syntax implies the arrangement of code into manageble blocks. This could easily support an mvp/mvc structure or any other.
    Alternatively, use an underscore or a space as the seperator. I personally prefer this for readability.
    The advantage of an underscore however, is that you don’t have to wrap your function calls in square brackets.

    You might be thinking, well what if my function names are really long, then this would make every call ['a very long function name . anothr very long function name']();
    Answer: So what! This actually performs quicker than parent.child.subchild(); Besides, when you minify your code to production, most of your function names will be ['a.b.c'](); etc…

  43. Pingback: Todo-App: 1. Vorbereitungen vornehmen

  44. Can someone here tell me, how can I get the name of the current namespace context as a string value?

    E.g.

    var subsys1 = {};

    var nextIdMod = function(startId) {
    var curNamespace = someFunc();
    // Now curNamespace = “subsys1″;

    ………
    };

    nextIdMod.call(subsys1);

  45. Hi, thank you for this brilliant post! Just want to advice you that the two links James Edwards: My Favorite JavaScript Design Pattern are broken. Cheers

  46. Pingback: Namespace in Javascript | Hot Proton

  47. Pingback: 基本的jQuery插件设计模式 | 徐达峰个人博客

  48. Pingback: Web Programming Blog

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