【发布时间】: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