JavaScript 组织
我在 javascript 代码中遇到了此问答组织。
var DED = (function() {
var private_var;
function private_method()
{
// do stuff here
}
return {
method_1 : function()
{
// do stuff here
},
method_2 : function()
{
// do stuff here
}
};
})();
目前我正在这样做,
var DED = new Object;
DED = {
sidebar : {
method_1 : function (data){
//some stuff
},
method_2 : function(data){
//do more
}
},
main : {
//.......
},
globalVariables : {
//...
}
}
其中一个比另一个有什么优势?
警告:这里是新手。
I came across this Q/A on javascript code organisation.
var DED = (function() {
var private_var;
function private_method()
{
// do stuff here
}
return {
method_1 : function()
{
// do stuff here
},
method_2 : function()
{
// do stuff here
}
};
})();
Currently I do this,
var DED = new Object;
DED = {
sidebar : {
method_1 : function (data){
//some stuff
},
method_2 : function(data){
//do more
}
},
main : {
//.......
},
globalVariables : {
//...
}
}
What is the advantage of one over the other?
Warning: newbie here.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如前所述,该方法使用闭包来实现私有函数和数据。它是构造函数方法(如下)的替代方法。例如,
使用问题中显示的 DED 方法,没有构造函数。相反,该函数返回一个从对象字面量创建的对象。该对象中的函数将私有变量和方法封闭在其中。
As indicated, that method uses closures to implement private functions and data. It's an alternative to the constructor method (below). E.g.
With the DED method shown in your question, there is no constructor. Rather the function returns an object created from an object literal. The functions in that object have the private variable and method closed into them.
从匿名自调用函数 (function(){})() 返回的是您为“模块”(DED) 发布的接口。
DED.method_1() 是公共的。 private_method/private_var 无法从外部访问,但自调用函数内部的所有内容都可以访问它们。
如果您喜欢这种访问控制,那么这是防止其他开发人员意外弄乱模块内部结构的好方法。在很多情况下,我只是采用命名约定,例如前导下划线来指示内部结构。
JavaScript 是非常动态的,如果有人真的想搞乱他们没有写访问权限的代码,他们将能够做到这一点。 编辑:事实证明,这是一个错误的假设,而不是构造函数或闭包中的私有数据的情况。请参阅:http://www.crockford.com/javascript/private.html
What you return from the anonymous self-calling function (function(){})() is the interface you publish for your "module" (DED).
DED.method_1() is public. private_method/private_var are not accessible from outside but everything inside of your self-calling function has access to them.
If you like this kind of access-control this is a good way to prevent other developer from accidentally messing with the internals of your module. In a lot of cases i'd just go for a naming convention like a leading underscore to indicate internals.
Javascript is very dynamic and if someone really wants to mess with code they have no write-access to they will be able to do so. Edit: This turns out to be a wrong assuption and not the case for private data in constructors or closures. Please, see: http://www.crockford.com/javascript/private.html