Namespace.js - simple namespaces in JavaScript

Written on

Namespace.js is an incredibly small, simple and fast JavaScript library which simplifies creating 'namespaces' in JavaScript.

Sometimes, developers want to organise their JavaScript modules into a 'custom namespace' so that they can reduce clutter in the global namespace, at the same time bringing some kind or organisational hierarchy to their code and modules.

One example is if you are modelling animals with JavaScript:

// Create a namespace called 'Animal.Mammal.Feline'
var Animal = window.Animal || {};
Animal.Mammal = window.Animal.Mammal || {};
Animal.Mammal.Feline = window.Animal.Mammal.Feline || {};

Animal.Mammal.Feline.Cat = {
    speak: function() {
        return 'Meow!';
    }
};

Animal.Mammal.Feline.Cat.speak(); // "Meow!"

That is all well and good, but to create the namespace "Animal.Mammal.Feline" we needed to write this ugly and repetative code:

var Animal = window.Animal || {};
Animal.Mammal = window.Animal.Mammal || {};
Animal.Mammal.Feline = window.Animal.Mammal.Feline || {};

Yuck!

The only thing namespace.js does is to allow you to replace that ugliness with something a little more readable and concise:

namespace('Animal.Mammal.Feline');

Just think of how quickly you can define namespaces for all of the different types of cats in the world in your next JavaScript web-app about cats:

namespace('Animal.Mammal.Feline.Cat.Tabby');
namespace('Animal.Mammal.Feline.Cat.Siamese');
namespace('Animal.Mammal.Feline.Cat.Persian');
namespace('Animal.Mammal.Feline.Cat.Oriental');

I have put namespace.js on GitHub for those who are interested in using it.


Comments