I'm trying to create nested class definitions in javascript to have only one global object.
At the moment we define new classes like this:
FOO.Navigation.Sidebar.Tooltip = function()
{
};
So in each function definition we have to repeat the whole nested class namespace:
FOO.Navigation.Sidebar.Tooltip.prototype.show = function()
{
/* do something here */
};
We introduced a namespace function to create the class.
FOO = { /* ... */ }
FOO.namespace = function(namespaceString)
{
var namespaceParts = namespaceString.split('.');
var currentRoot = FOO;
var index = 0;
// Skip the first namespacePart, if it is already "FOO"
if ("FOO" == namespaceParts[0])
{
index = 1;
}
var currentPart;
for(index; index < namespaceParts.length; index++)
{
// This is the next element in the namespace hierarchy.
currentPart = namespaceParts[index];
// Add a new map for the currentPart to the root (if it does not exist yet).
currentRoot[currentPart] = currentRoot[currentPart] || {};
// The currentPart will be the new root in the next loop.
currentRoot = currentRoot[currentPart];
}
return currentRoot;
};
Now we want to use this to create a more readable version of previous definitions which should look like this:
FOO.Navigation.Sidebar.Tooltip = function()
{
this.hallo = "world";
};
var tooltip = FOO.Navigation.Sidebar.Tooltip;
tooltip.prototype.show = function()
{
/* do something */
};
That would create a new global variable "tooltip" and we have to type the class name twice. So we thougth of using anonymous functions like this:
(function(tooltip) {
tooltip = function()
{
this.hello = "world";
};
tooltip.prototype.show= function()
{
/* do something */
};
}) (FOO.namespace("FOO.Navigation.Sidebar.Tooltip"))
This obviously don't work, because we assing a new function definition to "tooltip".
So my question is, if there is a way to write the class name only once without creating any more global variables.