4

使用以下构造,您可以拥有私有变量、公共和私有函数。那么为什么有各种不同的方法来创建命名空间呢?

NameSpace 是否与具有相关行为和范围的函数完全不同?

我看到了不污染全局命名空间的意义,例如浏览器中的窗口对象,它会创建过多的功能,但这也可以通过以下方式实现..

似乎我错过了一个基本点..

// 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

1 回答 1

4

关键是您可能有多个函数,但您只想用一个变量(“命名空间”)污染全局范围。

// 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
    };
}());

此外,Felix 是对的,您的“私有”实例函数实际上是非常公开的。如果您想要实际的私有方法,请参阅Crockford 的“JavaScript 中的私有成员” 。

于 2011-07-08T20:28:00.000 回答