开发者

Why Javascript Namespaces if prototypal inheritance provides it all

开发者 https://www.devze.com 2023-03-18 04:03 出处:网络
Using the below construct you can have private variables, public & private functions. So why have all the various ways to create a namespace ?

Using the below construct you can have private variables, public & private functions. So why have all the various ways to create a namespace ?

Is开发者_JAVA百科 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").

// 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 public. See Crockford's "Private Members in JavaScript" if you want actual private methods.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号