如果原型继承提供了这一切,为什么要使用Javascript名称空间
使用下面的构造,您可以拥有私有变量、公共函数和私有函数。那么,为什么有各种各样的方法来创建名称空间呢 名称空间是否与具有关联行为和范围的函数完全不同 我看到了不污染全局名称空间的意义,例如浏览器中的窗口对象,它将创建过多的函数,但这也可以通过以下方法实现 好像我错过了一个基本点如果原型继承提供了这一切,为什么要使用Javascript名称空间,javascript,namespaces,prototypal-inheritance,Javascript,Namespaces,Prototypal Inheritance,使用下面的构造,您可以拥有私有变量、公共函数和私有函数。那么,为什么有各种各样的方法来创建名称空间呢 名称空间是否与具有关联行为和范围的函数完全不同 我看到了不污染全局名称空间的意义,例如浏览器中的窗口对象,它将创建过多的函数,但这也可以通过以下方法实现 好像我错过了一个基本点 // Constructor for customObject function customObject(aArg, bArg, cArg) { // Instance variables are
// 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();
关键是您可能有多个函数,但您只想用一个变量(“名称空间”)污染全局范围
另外,Felix是对的,您的“私有”实例函数实际上是非常公开的。查看是否需要实际的私有方法。现在将构造函数
customObject2
放在哪里?顺便说一句,instanceFunctionAddAll
在经典的OO意义上不是“私有的”。它可以从外部调用。啊哈,这是有道理的。谢谢,谢谢。我在某处看到了这一点,感到困惑。我可以理解匿名函数-->函数(){}。但是整个构造包含在另一个(->function(){}@PlanetUnknown:用于立即执行匿名函数。这用于创建新的作用域。JavaScript只有函数作用域。这样,CustomObject
和CustomObject2
不会污染全局命名空间,只能通过窗口访问。命名空间
。这回答了您的问题吗?@PlanetUnkn如果您想要一篇关于该结构的深入博客文章,请访问own
// 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
};
}());