If you do a lot, or a little, Javascript development I am sure you have found yourself at a point where your js files are getting out of control. This happens even if the project that you are working on is relatively small, but it quickly gets to a point where it becomes hard to find anything and not even the new Visual Studio 2012 Javascript tools can help you. There is no dropdowns to navigate to custom functions, the only help you get is the search.

I’ve worked with the Google Maps JS API for a couple of different personal and work related projects and always liked the way they use namespaces when creating their objects like this:

var map = new google.maps.Map();

Even if you try downloading their API and beautify the code you probably won’€™t find how this is done, so I started thinking a way to do it myself.

After much trying I finally found a way to simulate .NET namespaces in Javascript.
The code I show below requires jQuery, but you could replace the each loop with a for instead if you are one of those weird developers not using jQuery yet.

// Create the namespace
var Lerones = Namespace('Javier.Lerones');
// The function that simulates .NET namespaces
function Namespace(n) {
    var names = n.split('.'),
        w = window;
    // Loop through all the names
    $.each(names, function(i, p) {
        w[p] = w[p] || {};
        // Creates window.Javier and window.Lerones
        w = w[p]; // Magic!
        // replaces the window object with the new parent
        // (window is the default parent for all objects)
        // for window.Javier doesn't need to do anything
        // for window.Lerones, replaces window with Javier
    return w;
    // Returns window.Javier.Lerones
// And now we can use this namespace to create custom objects:
Lerones.Search = function() {
    // Custom object logic
// Initialize the Search object like this:
var newSearch = new Javier.Lerones.Search();

Note that I only created two levels in the namespace, but there is nothing preventing your from doing something like

var Oceans = Namespace('Porcelina.Of.The.Vast.Oceans');

So start renaming your javascript files to things like:


and enjoy the feeling