adams.co.tt

Namespacing in JavaScript

30th May 2012

JavaScript’s global variables are evil, and namespacing is a good thing. However, as I regularly move from project to project, I find myself rewriting the code to help manage namespaces again and again. Every time I search for something reusable, I find conventions that require unpleasant boilerplate.

I started a little personal project, and ended up writing this. Hopefully somebody might find it useful.

Grab the source here.

Include it in your document like so:

<script src="/path/to/n.js" type="text/javascript"></script>

Register objects and classes like so:

n('foo.bar.baz', function(s) {
  s.Person = function () {
    this.greet = function () {
      alert('hello');
    };
  };
});

Reference registered objects and classes like so:

var myPerson = new foo.bar.baz.Person();
myPerson.greet();

That’s all there is to it!

UPDATE: A minified version can now be found here. Thanks Scott Hamper!

blog comments powered by Disqus