This is better for defining a namespace in javascript (and in Meteor):
MyNamespace = (typeof MyNamespace === 'undefined')? {} : MyNamespace;
Unfortunately it's an ugly monster (syntactically). I hope namespaces will be natively supported soon in Javascript (maybe together with classes and modules).
Usage
You can place it at the start of your files, than add your variables to it. For example:
File MyNamespace/greeting.js
:
MyNamespace = (typeof MyNamespace === 'undefined')? {} : MyNamespace;
MyNamespace.greeting = 'hello world';
// ...
File MyNamespace/myFunction.js
:
MyNamespace = (typeof MyNamespace === 'undefined')? {} : MyNamespace;
MyNamespace.myFunction = function() {
// ...
}
What's wrong with MyNamespace = {};
?
The point is that if you have a namespace defined on more than one file (note that inside an environment like Meteor, if you start to organize your code splitting it on multiple js files, this will happen likely) with MyNamespace = {};
the file that will be loaded for last will overwrite all definitions in previous ones.
For example:
File /client/controllers/HomeController
:
Controllers = {}; // define namespace Controllers
Controllers.HomeController = ...
// ...
File /client/controllers/LoginController
:
Controllers = {}; // define namespace Controllers
Controllers.LoginController = ...
// ...
With Meteor, LoginController
will be loaded last for the alphabetic order and the instruction Controllers = {};
clears the HomeController
definition that will be lost.
The solution above will prevent this.