javascript interactive

JavaScript Interactive — a console crash course


5.1 Namespaces

Warning: Your browser may be outdated or unsupported.

The JavaScript console is known to display some of the examples incorrectly in Internet Explorer 8 or older.

JavaScript contains no proper namespace mechanism, so a work-around is used instead:

  1. Declare a global variable with an object value.
  2. Add additional symbols as properties to this object (one way or another).
>>>
var MyOrg = MyOrg || {};

  
A global namespace declaration, using an organization or project name. The variable is only modified if previously undefined, so the declaration can be placed at the top of any source code file.
>>>
MyOrg.one = function () {
    return 1;
};

  
When the namespace has been declared, properties can be added almost in any order. And the code can be split across files without issues.
>>>
MyOrg.two = function () {
    return 2;
};

  
The major drawback with this method is namespace repetition, which also makes for worse minification. As functions are anonymous, exception stack traces also become hard to read.
>>>
(function () {
    function one() {
        return 1;
    }
    function two() {
        return 2;
    }
    var obj = window.MyModule || {};
    obj.one = one;
    obj.two = two;
    window.MyModule = obj;
})();

  
Another variant is to place all code inside an anonymous initializer function. This protects the global scope, so variables and functions can be declared rather freely. But in the end, everything must be exported to the global scope, i.e. the window object in browsers.
>>>
(function (window, undefined) {
    /* initializer code here */
})(this);

  
Clever use of arguments to the initializer function ensures that window is always bound to the global scope, that undefined is indeed undefined, and that both names are bound to local variables that can be minified.
>>>

Index 1 2 3 4 5 6 7 8