Over the past 10 or so years I’ve written a lot of JavaScript. From very early on, at Caplin Systems, I had to write things in a way which ensured that code was clear, usable, discoverable, reusable, extensible and can easily built upon. One of the concepts that was used was to put code within a namespace. This ensured that you couldn’t accidentally override a function in the global window namespace and also meant that the namespace would describe the sort of functionality contained within. I’ve continued to use this concept in various forms but just realised that I’ve never actually shared how I do this. So here goes.

It’s actually really simple. I’ve got two functions that I use, and I’ve recently ported over to the com.pusher namespace since I’m creating demos for my work (and play). The first creates some default namespace objects and then defines a namespace function that can be used from then on to create any other namespace objects.

/**
 * @namespace
 * Top-level namespace to stop namespace clutter.
 */
if(!window["com"]) {
  window["com"] = {};
}

// create pusher ns
if(!com.pusher) {
  com.pusher = {};
}

/**
 * Ensures that a namespace exists.
 * @param {String} namespace The namespace to check for and create if required.
 *
 * @return {Object} The existing or new namespace.
 */
com.pusher.namespace = function(namespace) {
  var parts = namespace.split(".");
  var context = window;
  var nsPath = "";
  for(var i = 0, l = parts.length; i < l; ++i) {
    var name = parts[i];
    if(!context[name]) {
      context[name] = {};
      context[name].__namespace = name;
    }
    nsPath += name + ".";
    context = context[name];
    if(!context.__namespace) {
      context.__namespace = nsPath.substring(0, nsPath.length-1); // trim off '.'
    }
  }
  return context;
};

A quick example of this might be:

com.pusher.namespace("my.new.namespace");

my.new.namespace.SomeClass = function() {
};
/* define methods etc. */

Then you can access the class anywhere using:

var instance = new my.new.namespace.SomeClass();

The second function that I’ve only just started to use takes a leaf from node.js. It in that it passes in an exports variable which represents the newly created namespace and then you can add items to that namespace.

Note: I’d previously called the exports variable called export but it would appear this is a reserved word in Safari & Firefox

com.pusher.define = function(namespace, definition) {
  var exports = {};
  definition(exports);

  var nsObject = com.pusher.namespace(namespace);
  for(var thingToexports in exports) {
    nsObject[thingToexports] = exports[thingToexports];
  }
};

You’ll noticed that it uses the com.pusher.namespace function to create the namespace object. The usage of this is then as follows:

com.pusher.namespace("my.new.namespace", function(exports) {

  var SomeClass = function() {
  };
  /* define methods etc. */

  exports.SomeClass = SomeClass;
});

The class can then be accessed in the same way as shown previously:

var instance = new my.new.namespace.SomeClass();

I like this last way of doing things as you declare the namespace at the top and wrap everything in a function. You then can pick what you want to expose to the outside world by just adding it to the exports variable.

I’d be interested to hear what you think about this approach. Do you have a better one?

Related posts:

  1. Making cross domain JavaScript requests using XMLHttpRequest or XDomainRequest
  2. Using Fiddler to help develop cross domain capable JavaScript web applications
  3. A Career Using JavaScript
  4. Adding a real-time "Who’s shopping?" widget to an ASP.NET Web App
  5. Defining the Kwwika API
Tagged with:
 
  • Cool

    Congrats on reinviting a wheel that has been solved by no less than 1,000,00 other JavaScript developers!  You should be proud!

  • Laura_

    WOW!  Is this a post on namespaces in JavaScript?  WHAT A GREAT AND NOVEL IDEA!   May I pleeeease fork this on GitHub?   

    The world has languished without this functionality in JavaScript for so long only because the great Phil — the architect, the visionary, the dreamer — hadn’t yet had time to make his mark.  But now he has.  What will Phil dream up next?

  • http://www.leggetter.co.uk Phil Leggetter

    Had a couple of comments by anonymous-no-identity trolls on this post. I’d normally delete (well I have) and ignore but interestingly enough the two comments asked the same question. And if they’d been phrased in a non-troll-like way would have been valid questions. The question summarised was

    > Why re-invent the wheel. JavaScript namespacing has already been solved by numerous developers and in numerous JavaScript libraries.

    This has most definitely been solved before. The first time I remember seeing namespaces in JavaScript outside of Caplin’s codebase was in the Dojo library. The only other libraries I use regularly at the moment are the Pusher JavaScript library and jQuery. In the Pusher library everything sits off the Pusher object. In jQuery everything sits off of the jQuery.fn object. The latter does run the risk of namespace cluttering in a large application.

    I’ve “re-invented the wheel” (well, I first used this code years ago but have only just published it) because I don’t always use a JavaScript library. Sometimes I write entirely my own code and I want to include two useful functions `namespace` and `define` which I can use for package/namespace management. I’ve supplied them in their entirity so others can copy and paste if they think they would be useful.

    Finally I asked “What do you use?”. I want to know what other solutions are out there. I’d be happy to switch if there was a small reusable library that offered something similar or better.

  • Dan Welch

    Huh… a blog post about a namespace utility in JS?   

    Google shows 7,500,000 results for similar articles.   It’s retarded that your poor employer had to pay you to create this utility.  Grab a library that solved this and move on.  Fact: 99% of complaints about library “bloat” are developers overly eager to recreate basic functionality on their own.  

  • Rich123

    LOL @ DAN

    HEY PHIL – CAN YOU CREATE A “COLOR PICKER” WIDGET NEXT?  THAT WOULD BE GROUNDBREAKING AND ALSO AWESOME.

  • http://www.leggetter.co.uk Phil Leggetter

    I know I shouldn’t let it bother me but replies by @7c2e8bead74c1673d9eca32c7f2074c1:disqus and @4b3c509740db059d25053170259c2b97:disqus are  a bit annoying. Dan points out that there are a lot of other solutions to this. But what’s the point in saying it the way he does? It’s just thoughtless and rude. The last paragraph of this post states:

    > I’d be interested to hear what you think about this approach. Do you have a better one?

    In his response it would be much better if he said. “No point reinventing the Wheel Phil. You are much better using library X, Y or Z. And here’s why…”.

    @Rich123:disqus - What is the point at all. And the CAPSLOCK things is just clearly indicates you are TROLLING.

    When I wrote this post I did do a quick search on Google for similar functions. I honestly didn’t find anything. I’ve just done another search for “javascript namespace utility” (http://www.google.co.uk/search?sourceid=chrome&ie=UTF-8&q=javascript+namespace+utility) and I’ve found a few very similar functions but none of them are that old (maybe it’s just Google placing more weight on newer posts – indeed I’m in the top 5).

    * Jan 2010 - http://2007-2010.lovemikeg.com/2010/01/20/responsible-javascript-namespaces/
    * Jan 2011 - http://elegantcode.com/2011/01/26/basic-javascript-part-8-namespaces/
    * Jan 2011 - http://leahayes.wordpress.com/2010/01/19/prototypejs-extension-namespaces-for-javascript/
    * Jan 2011 - http://blog.stannard.net.au/2011/01/14/creating-namespaces-in-javascript/

    Looks like people decide to do this in January.

    I don’t have a problem with people writing functionality of their own. Especially if it’s small utility methods. Sometimes you don’t want to include a full blown JavaScript library just for two methods. So, write your own. Plus it’s fun and isn’t that one of the reasons we write code in the first place?

  • Quagmire88

    “Sometimes you don’t want to include a full blown JavaScript library just for two methods.”

    WRONG, idiot.  Junior developers always fail to realize that simple apps quickly become sophisticated apps. 

    And while it might be fun for you to be the millionth person to recreate the wheel, remember that the libraries have solved the first round of bugs/shortcomings that your implementation will inevitably have, and it’s easier for the next developer at your company to pick up a library than it is to learn your stupid ass custom library (because the code will grow).

    Additionally, don’t hate on a library because it adds 20k to your app.  There’s no perceptible difference to the user.

    Finally, use Dojo.  It has all this and a bag of chips.

Set your Twitter account name in your settings to use the TwitterBar Section.