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.
-
This would be much easier to answer if the first and the second example would use the same names.jwueller– jwueller2010年12月28日 23:22:44 +00:00Commented Dec 28, 2010 at 23:22
-
1minor remark: you don't need to initialize DED as a new Object. The object-literal notation in the next line will do the same thing. Just don't forget the 'var' if you want local scope.kioopi– kioopi2010年12月28日 23:31:02 +00:00Commented Dec 28, 2010 at 23:31
-
@kioopi if you did forget 'var', does that mean it would bind DED to the window.DED property (assuming it's running in a browser)?jamiebarrow– jamiebarrow2011年08月25日 11:02:19 +00:00Commented Aug 25, 2011 at 11:02
-
@jamiebarrow yes, exactly. it's a very bad part of javascript to default to global scope.kioopi– kioopi2011年08月27日 06:18:40 +00:00Commented Aug 27, 2011 at 6:18
2 Answers 2
As indicated, that method uses closures to implement private functions and data. It's an alternative to the constructor method (below). E.g.
var DED = new (function()
{
var private_var;
function private_method()
{
// do stuff here
}
this.method_1 = function()
{
// do stuff here
};
this.method_2 = function()
{
// do stuff here
};
})();
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.
1 Comment
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