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!
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!
Share Improve this question edited Jul 10, 2015 at 21:34 Pointy 414k62 gold badges594 silver badges627 bronze badges asked Jul 10, 2015 at 21:34 John DoeJohn Doe 531 silver badge3 bronze badges 1- Self invoke functions keep scope/context of inner functions in the first example. See stackoverflow./questions/19850234/… for more info about Node.js modules. – adamkonrad Commented Jul 10, 2015 at 22:18
3 Answers
Reset to default 5Your 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.
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
};
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.