javascript - What's the benefit to export functions with self invoke functions than direct return -


i've checked lot of codes , i've saw lot of people doing

module.exports = (function(){   return {     functiona: function() {        }     },     functionb: function() {      }   }; })(); 

so, why not do

module.exports = {   functiona: function() {    },   functionb: function() {    } }; 

thanks!

your first example allows hide variables within own closure scope can shared return object's methods. example, if did following...

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

the above example shows x variable protected , shared between addtotwo , subtractfromtwo. second example allow make x part of object without same protection.

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

x can altered in example.


Comments