如果原型继承提供了一切,为什么还要使用 Javascript 命名空间
使用下面的构造,您可以拥有私有变量、公共变量和公共变量。私人职能。那么为什么有各种各样的方法来创建命名空间呢?
命名空间与具有相关行为和功能的函数完全不同吗?范围 ?
我认为不污染全局命名空间(例如浏览器中的窗口对象)会创建大量函数,但这也可以通过下面的方法来实现。
似乎我错过了一个基本点。
// 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();
Using the below construct you can have private variables, public & private functions. So why have all the various ways to create a namespace ?
Is 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();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
关键是您可能有多个函数,但您只想用单个变量(“命名空间”)污染全局范围。
另外,菲利克斯是对的,你的“私有”实例函数实际上是非常公开的。如果您想要实际的私有方法,请参阅 Crockford 的“JavaScript 中的私有成员”。
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").
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.