Last Updated: September 09, 2019
·
2.011K
· gerardsans

JavaScript - Using Namespaces

Sons of JavaScript Collection | this article

You can simulate namespaces as seen in other languages creating JavaScript objects. This will both help structure your application and reduce name collisions.

Creating a company namespace

In order to create the following namespace you can use two notations

MyCompany.MyApp.MyModule.myVariable
MyCompany.MyApp.MyModule.myFunction()

Literal notation

Using this notation first you create the object and then start creating the properties as you go.

var MyCompany = {
    MyApp : {
        MyModule: {
           myVariable: 1,
           myFunction: function() { return 2;}
        }
    }
}
console.log(MyCompany.MyApp.MyModule.myVariable) // 1
console.log(MyCompany.MyApp.MyModule.myFunction())  // 2

Two steps notation

Using this notation you create empty objects and for the last level you use a literal object.

var MyCompany = {};
MyCompany.MyApp = {};
MyCompany.MyApp.MyModule = {
   myVariable: 1,
   myFunction: function() { return 2;}
};
console.log(MyCompany.MyApp.MyModule.myVariable)  // 1
console.log(MyCompany.MyApp.MyModule.myFunction())  // 2

Allowing extensibility

Library developers sometimes need to handle special use-cases. In this case we want to start from a previous object definition (we don't want to worry about scripts order or we want to co-exist with older versions). If you need that behaviour you could change the initial line to

var MyCompany = MyCompany || {};

Taking advantage of falsy objects and JavaScript eager comparision evaluation this code uses a previous definition of MyCompany or creates a new one if MyCompany evaluates to falsy (empty string, the number 0, null, NaN, a boolean false, or undefined).

Sons of JavaScript Collection | this article

5 Responses
Add your response

This creates a lot of overhead in the system, and isn't really doing anything like what namespaces do in object oriented languages. ThisThe industry best practice is to use commonJS style module definitions.

var MyCompany.MyModule =(function module(window, undefined, dependency){
           // assign values and methods to exports using exports.myValueOrMethod 
           return exports;
}(window, undefined, dependency))
over 1 year ago ·

Scope isolation is related but not exactly the same concept as namespaces in JavaScript. I will write about JavaScript Modules and Sandboxing in another article.

over 1 year ago ·

again, this is much better solved using a real module system like CommonJS, AMD or ES6 modules.

over 1 year ago ·

Yes, as Benjamin pointed. It's better to use Module systems like ES6

over 1 year ago ·

Only if you could... For the moment ES6 modules will be transpiled to ES5 using a similar approach. Look into the transpiled code and be shocked =)

over 1 year ago ·