【问题标题】:Why Javascript Namespaces if prototypal inheritance provides it all如果原型继承提供了一切,为什么还要使用 Javascript 命名空间
【发布时间】:2011-07-08 20:22:16
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • 现在你会把构造函数customObject2放在哪里?顺便提一句。 instanceFunctionAddAll 不是经典 OO 意义上的“私有”。可以从外部调用。
  • 啊哈,这很有道理。谢谢。

标签: javascript namespaces prototypal-inheritance


【解决方案1】:

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

// 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's "Private Members in JavaScript"

【讨论】:

  • 谢谢。我在某个地方看到了这个并且感到困惑。我可以理解匿名函数--> function(){}。但是整个构造都包含在另一个(-->function(){}
  • @PlanetUnknown:用于立即执行匿名函数。这用于创建新范围。 JavaScript 只有函数作用域。这样,CustomObjectCustomObject2 就不会污染全局命名空间,只能通过window.namespace 访问。这能回答你的问题吗?
  • @PlanetUnknown 如果您想深入了解该结构,请查看benalman.com/news/2010/11/…
猜你喜欢
  • 2013-03-10
  • 1970-01-01
  • 2011-01-06
  • 1970-01-01
  • 2011-11-09
  • 2013-05-10
  • 2020-11-24
  • 1970-01-01
  • 2017-02-06
相关资源
最近更新 更多