Short answer
The way that I learnt it was (applies to namespace creation as well):
// Check if the com namespace does not exist:
if (!com) {
var com = {};
}
// Check if your namespace does not exist:
if (!com.myNamespace) {
var com.myNamespace = {};
}
Some information that I learnt (so far)
According to a book that I'm reading, the com namespace is a container for commercial products (by that, I mean websites, libraries etc).
The namespace was originally created to hold domains. However, today you'll find com.* in libraries, databases or even frameworks!
It is currently operated by VeriSign, and has been in existence for 33 years now!
Long answer
First, we need to make sure that the main namespace exists. We'll do this checking if com does not exist:
if (!com) {
var com = {};
}
com is the most common namespace to check. However, we can check any namespace.
We could skip this part, but it would be really irritating to get all of your functions mixed up.
If com does not exist, then create it.
var com = {};
Lastly, we need to check if myNamespace exists. We'll be using the same method for the com, but this time, we'll add com. before myNamespace.
if (!com.myNamespace) {
var com.myNamespace = {};
}
The reason why we add com. before our namespace declaration, is that the com namespace is made at the second level and myNamespace is made on the third level.
I recommend that you add a Fourth level namespace for your project.
This will ensure that:
your project has it's own namespace (if myNamespace is taken).
your project will not be mixed in with other projects (e.g. com.projectA.other and com.projectA.yourProject).
your functions will not get mixed up (e.g. you have a function called write).
Now, your code
You're nearly there! Here is how I would look at it:
if (!TOP) {
// Reinitialize your TOP Namespace here:
var TOP = {};
}
if (!TOP.middle) {
// Reinitialize your MIDDLE Namespace here:
var TOP.middle = {};
}
if (typeof TOP.middle.realModuleName == "function") {
new TOP.middle.realModuleName ();
}
else {
// Redefine your function here (you never know ;) )
}
new Top.middle.realModuleName(arg1, arg2)is called, inside realModuleName will check if arg2 is passed (assuming arg2 is required). It arg2 is not passed, throw an error.