4

I've checked a lot of codes and I've saw a lot of people doing

module.exports = (function(){
  return {
    functionA: function() {

      }
    },
    functionB: function() {

    }
  };
})();

so, why not just do

module.exports = {
  functionA: function() {

  },
  functionB: function() {

  }
};

Thanks!

Pointy
  • 405,095
  • 59
  • 585
  • 614
John Doe
  • 43
  • 1
  • 3
  • Self invoke functions keep scope/context of inner functions in the first example. See http://stackoverflow.com/questions/19850234/node-js-variable-declaration-and-scope for more info about Node.js modules. – adamkonrad Jul 10 '15 at 22:18

3 Answers3

5

Your first example allows you to hide variables within its own closure scope that can be shared with your return object's methods. The For example, if you did the following...

var foo = (function(){
   var x = 2;
      return {
        addToTwo: function(y){
        return x + y;
      },
      subtractFromTwo: function(y){
        return x - y;
      }
   }
};

The above example shows that the x variable is protected and shared between addToTwo and subtractFromTwo. The second example only will allow you to make x as part of the object without the same protection.

module.exports = {
  x: 3,
  functionA: function() {
     return this.x;
  },

};

x can be altered in this example.

mitch
  • 1,821
  • 14
  • 14
1

Those are exactly the same. It's a stylistic decision.

According to the Node.js docs:

Variables local to the module will be private, as though the module was wrapped in a function.

You could also do it this way:

module.exports.functionA = function() {

};

module.exports.functionB = function() {

};

Or:

// either method for creating a function works
function functionA () {}

var functionB = function () {} 

module.exports = {
    functionA : functionA,
    functionB : functionB
};
ChadF
  • 1,750
  • 10
  • 22
  • Why was this downvoted? It's an informative answer. It doesn't really answer *why* people do that, but there's no good answer for that part of the question anyway. – Pointy Jul 10 '15 at 21:49
0

One of the greatest advantages of directly invoked functions is the use of closures which cannot be obtianed in a separate manner, so literally they are not the same.

KAD
  • 10,972
  • 4
  • 31
  • 73