Why Javascript namespace if prototype inheritance provides all this

Using the construction below, you can have private variables, public and private functions. So why do you have all sorts of ways to create a namespace?

Is NameSpace radically different from a function with corresponding behavior and scope?

I see that do not pollute the global namespace, for example. window in browsers with many features that could be created, but this can be achieved even lower.

It seems that I am 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(); 
+4
source share
1 answer

The fact is that you can have several functions, but you want to pollute the global area with only one variable ("namespace").

 // Wrap in a immediately-executing anonymous function to avoid polluting // the global namespace unless we explicitly set properties of window. (function () { function CustomObject(/*...*/) { /*...*/ } // Add methods, static methods, etc. for CustomObject. function CustomObject2(/*...*/) { /*...*/ } // Add methods, static methods, etc. for CustomObject2. var CONSTANT_KINDA = "JavaScript doesn't really have constants"; // Create a namespace, explicitly polluting the global scope, // that allows access to all our variables local to this anonymous function window.namespace = { CustomObject: CustomObject, CustomObject2: CustomObject2, CONSTANT_KINDA: CONSTANT_KINDA }; }()); 

Also, Felix is ​​right, your "private" instance function is actually very popular. See Crockford "Private Members in JavaScript" if you want private private methods.

+4
source

All Articles