Are there any dangers associated with using JavaScript namespaces?

Are there any dangers / caveats to be aware of when creating JavaScript namespaces?

Our project is quite expansive, and we run many JavaScript files (20+, expecting more). It is not possible to maintain code compatibility without using namespaces, so we implement them like this:

var namespace1 = {

  doSomething: function() {
    ...
  },

  doSomethingElse: function() {
    ...
  }

}

Then, to create hierarchies, we link them like this:

var globalNamespace = {
  functions1: namespace1,
  functions2: namespace2,
  ...

}

, "", JS , . , , , , , - . JS-, . , .

- , "" ? ?

+4
4

, , ,

window.namespace1
window.namespace2
window.globalNamespace
window.globalNamespace.namespace1
window.globalNamespace.namespace2

, -, clobbers window.namespace1, clobber window.globalNamespace.namespace1

:

:

namespacing = {
    init: function(namespace) {
        var spaces = []; 
        namespace.split('.').each(function(space) {
            var curSpace = window,
                i;  

            spaces.push(space);
            for (i = 0; i < spaces.length; i++) {
                if (typeof curSpace[spaces[i]] === 'undefined') {
                    curSpace[spaces[i]] = {}; 
                }   
                curSpace = curSpace[spaces[i]];
            }   
        });
    }
};

:

namespacing.init('globalNamespace.namespace1');

globalNamespace.namespace1.doSomething = function() { ... };

, , .

+3

, , .

, () , require.js? "" , :

require(["helper/util"], function() {
  //This function is called when scripts/helper/util.js is loaded.
});

Require.js , .

+2

, . , ; . - . , , Foo.Bar.Test.Namespace2.Function, , .

+1

, , "" . - , . , Acme co , ACME .

:

if (!window.ACME) { window.ACME = {} }

, , .

ACME.Foo = {
  bar: function () { console.log("baz"); }
}

, .

if (!window.ACME) { window.ACME = {} }
if (!ACME.Foo) { ACME.Foo = {} }

, , , , , .

+1

All Articles