The first one-ish
As quoted from this post:
- In the top-level code in a Node module, "this" is equivalent to module.exports.
Therefore the 2 may seem equivalent. But, they're not - in your second example, you are changing the object referenced by "module.exports". This is dangerous since any prior modifications that you have made to the original object previously referenced by "module.exports" within the same module (thanks Kevin for letting me know this wasn't clear) will no longer be available when requiring. In the future, should someone want to add a function using the other method, and make it available before your re-assignment, they might find themselves unable to access it while having some correct looking code.
Also - by allowing yourself to believe the 2nd method has the same effect, you may be tempted to do something like:
module.exports = {
functionName1
};
// code, code, code
module.exports = {
functionName2
};
Which will obviously strip you of acces to the original functionName1
method.
Of course, you may add both of the functions to the new object at the same time but what if they're just not available in your scope (e.g. they've been definied inside another function)? You'll still have to use the 1st method anyway at the time when the function is available.
Both methods obviously work. I am recommending the 1st one since to me it's both the clearer and less error prone.
However
Since this
is context dependent, drop it all together and stick to module.exports
. You'll end up with something like:
module.exports.functionName = function(params) {
//do something
};
or
function mySimpleFunction(params){
//do something
}
module.exports.functionName = mySimpleFunction;
(in case your concern was with associating the declared function)