Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Namespace declaration

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?

like image 320
at. Avatar asked Sep 06 '26 09:09

at.


2 Answers

I've seen this convention used several places.

window.YourNamespace = window.YourNamespace || {};
like image 163
lincolnk Avatar answered Sep 09 '26 16:09

lincolnk


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.

like image 38
Rene Saarsoo Avatar answered Sep 09 '26 16:09

Rene Saarsoo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!