Are there any dangers associated with using JavaScript namespaces?

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

Our project is fairly expansive and we are running a lot of JavaScript files (20+, expecting more). It is impossible to have any code maintainability without using namespaces, so we are implementing them like so:

  • Best workflow for developing npm packages that depend on each other
  • Bower “Git not in the PATH” error
  • Angular.js Tutorial using the Node.js webserver
  • login to jenkins using ajax/javascript
  • Add 'scripts' folder to .gitignore in Aurelia project?
  • Deployment Strategy for Require JS Optimized/Concatenated Website Files
  • var namespace1 = {
    
      doSomething: function() {
        ...
      },
    
      doSomethingElse: function() {
        ...
      }
    
    }
    

    And then to create hierarchies, we link them like so:

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

    This works fine, but it is essentially a “trick” to make JS behave as if it did have namespaces. Although this method gets used a lot, most literature on this seems to focus on how to do it, and not whether there are any possible drawbacks. As we write more JS code, this is quickly becoming an integral part of the way our system works. So it’s important that it works seamlessly.

    Were there any situations in which this “induced” namespace system caused you errors, or otherwise needed special attention? Can we safely expect identical behaviour across all browsers?

  • Phonegap - automatically including correct cordova
  • How does GitHub change the URL without reloading a page?
  • Bundler for javascript, or how to source control external javascript files
  • Architecture for managing JSON files in a javascript project: Internal database vs.git
  • Json Diff Patch Javascript - extjs
  • Angular2 .gitignore
  • 4 Solutions collect form web for “Are there any dangers associated with using JavaScript namespaces?”

    The way you define namespaces in your example it appears to create globals out of each namespace so you end up with

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

    So if you have anything that clobbers window.namespace1 it will also clobber window.globalNamespace.namespace1

    edit:

    Here’s how we got around this problem:

    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]];
                }   
            });
        }
    };
    

    Then you use it like this:

    namespacing.init('globalNamespace.namespace1');
    
    globalNamespace.namespace1.doSomething = function() { ... };
    

    This way you don’t have to introduce new global variables and you can confidently add to an existing namespace without clobbering other objects in it.

    Since you are basically adding functions to objects and those objects into other objects, I would expect each browser to handle this the same way.

    But if you want modularity, why not use a (relatively) simple framework like require.js? That will allow you and your team to write code in a modular fashion and allows the team to ‘import’ these modules where needed:

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

    Require.js will take care of dependencies, and it will also prevent polluting the global namespace.

    We use a similar system at work and it does the job just fine. I don’t see any drawbacks there could be; it’s just objects and properties. For that same reason, cross browser compatibility should be good. You can end up having to write some long names to resolve to a particular function, like Foo.Bar.Test.Namespace2.Function, but even then that can be solved by assigning it to a variable before hand.

    This is how I’d recommend doing it, so you stay out of the global scope entirely except for your “base” namespace. We do something similar where I work. Let’s say you work for Acme co, and want ACME to be your base namespace.

    At the top of every file, you’d include:

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

    Then you just go and define whatever you want in terms of that.

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

    If you want a deeper level of namespace, you just do the same thing for each level.

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

    This way each file can be tested independently and they’ll set up the namespace infrastructure automatically, but when you compile them together or if you test multiple files simultaneously, they won’t keep overwriting things that are already defined.

    Git Baby is a git and github fan, let's start git clone.