views:

46

answers:

4

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?

A: 

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.

Lloyd
What's the most popular namespace framework?
at
Namespace framework?
Lloyd
A: 
  var Utils = {
        namespace : function(name) {
                return window[name] = window[name] || {};
        }
  };

or if you prefer your way use:

if (typeof window.YourNamespace === 'undefined') {
    YourNamespace = {};
}
Sven Hecht
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?
at
sorry should have clarified that. The Utils class above is nicer because you can use it as follows: Utils.namespace("myGreatNewNamespace");
Sven Hecht
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.
Sven Hecht
A: 

I've seen this convention used several places.

window.YourNamespace = window.YourNamespace || {};
lincolnk
simplified version of what I wrote earlier.
Sven Hecht
+1  A: 

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.

Rene Saarsoo