Using the below construct you can have private variables, public & private functions. So why have all the various ways to create a namespace ?
Is the NameSpace that radically different than a function with associated behavior & scope ?
I see the point of not polluting the global namespace e.g. window object in browsers with the plethora of functions one would create, but that can be achieved by the below as well..
Seems I’m missing a fundamental point..
// Constructor for customObject
function customObject(aArg, bArg, cArg)
{
// Instance variables are defined by this
this.a = aArg;
this.b = bArg;
this.c = cArg;
}
// private instance function
customObject.prototype.instanceFunctionAddAll = function()
{
return (this.a + this.b + this.c);
}
/*
Create a "static" function for customObject.
This can be called like so : customObject.staticFunction
*/
customObject.staticFunction = function()
{
console.log("Called a static function");
}
// Test customObject
var test = new customObject(10, 20, 30);
var retVal = test.instanceFunctionAddAll();
customObject.staticFunction();
The point is that you might have more than one function, but you only want to pollute the global scope with a single variable (the “namespace”).
Also, Felix is right, your “private” instance function is actually very public. See Crockford’s “Private Members in JavaScript” if you want actual private methods.