3

What is the proper way to declare a namespace? I've just read "Developing Large Web Applications" and the author suggests using:

if (!window.YourNamespace) {
  YourNamespace = {};
}

seems easy enough.. but I see all the javascript libraries for declaring namespaces and alternate methods. Isn't there a standard way to do this? Any problems with the above?

1
  • It is currently more common practice for javascript developers to use a enclosed module format instead of defining objects on the global scope. Using module loaders such as require.js helps out with this. There are two different module formats to consider: AMD and/or CommonJS, and you can read more about it on the blog post Writing Modular Javascript by Addy Osmani. Commented Apr 12, 2013 at 13:07

7 Answers 7

2

I've seen this convention used several places.

window.YourNamespace = window.YourNamespace || {};
Sign up to request clarification or add additional context in comments.

1 Comment

simplified version of what I wrote earlier.
2

The mentioned namespace-declarating-way by book author is indeed quite good one. But when you need to repeat it in several files and the namespace has several subnamespaces, it can get quite tedious:

if (!window.Foo) {
  Foo = {};
}
if (!window.Foo.Bar) {
  Foo.Bar = {};
}
if (!window.Foo.Bar.Baz) {
  Foo.Bar.Baz = {};
}
etc...

Instead you should write a simple function that takes care of declaring the namespaces for you:

function namespace(ns) {
  var parts = ns.split(/\./);
  var obj = window;
  for (var i=0; i<parts.length; i++) {
    var p = parts[i];
    if (!obj[p]) {
      obj[p] = {};
    }
    obj = obj[p];
  }
}

Now you can declare the whole nested namespace with just one line:

namespace("Foo.Bar.Baz");

In ExtJS framework this is basically what Ext.ns() function does. I don't really know about other libraries.

Comments

0
  var Utils = {
        namespace : function(name) {
                return window[name] = window[name] || {};
        }
  };

or if you prefer your way use:

if (typeof window.YourNamespace === 'undefined') {
    YourNamespace = {};
}

3 Comments

Why is the second way better than the way I posted above? how does the first way work? I'm a little confused. Utils is the namespace and it's an associative array consisting of a function?
sorry should have clarified that. The Utils class above is nicer because you can use it as follows: Utils.namespace("myGreatNewNamespace");
the second is better because event though testing for !window.YourNamespace will catch the default case won't catch it if there is a global Variable YourNamespace = 1; and will overwrite YourNamespace = 0; You should always test for undefined if you want undefined. Also use === instead of == in these cases.
0

There is no standard way as you'll see between frameworks but they do go beyond the basics so that for example X.Y.Z, it will create all objects in that chain if they don't already exist.

Comments

0

bob.js handles namespaces like this:

bob.ns.setNs('YourNamespace', {

    /*define your members here. e.g.:*/
    method1: function () { /*...*/ }
});


// now, merge another, sub-namespace.
bob.ns.setNs('YourNamespace.YourSubNamespace', {

    method2 function () { /*...*/ }
});

//call methods:
YourNamespace.method1();
YourNamespace.YourSubNamespace.method2();

Comments

0

Automating namespaces declaration in javascript is very simple as you can see:

var namespace = function(str, root) {
    var chunks = str.split('.');
    if(!root)
        root = window;
    var current = root;
    for(var i = 0; i < chunks.length; i++) {
        if (!current.hasOwnProperty(chunks[i]))
            current[chunks[i]] = {};
        current = current[chunks[i]];
    }
    return current;
};

// ----- USAGE ------

namespace('ivar.util.array');

ivar.util.array.foo = 'bar';
alert(ivar.util.array.foo);

namespace('string', ivar.util);

ivar.util.string.foo = 'baz';
alert(ivar.util.string.foo); 

Try it out: http://jsfiddle.net/stamat/Kb5xY/ Blog post: http://stamat.wordpress.com/2013/04/12/javascript-elegant-namespace-declaration/

Comments

-1

Some example of namespace function:

namespace = function(ns){
    arr = ns.split(".")
    parent = window

    var temp

    while( ( temp = arr.shift()) !== undefined){
        parent[temp] = parent[temp] || {}
        parent = parent[temp]
    }
}

You can then use it as:

namespace("your.own.namespace")

your.own.namespace.Car= function () {

    this.speed = 30; 

}

1 Comment

This question doesn't contain any information that is not already provided by at least one of the other answers. Also it doesn't really answer the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.