Search code examples
javascriptcode-organization

javascript organisation


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.


Solution

  • 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.