Reputation: 9956
I have been converting some old javascript for use in a node.js module and it got me thinking about module pattern options.
I have seen a number of structures using exports. module.exports and even prototype, and it has left me wondering which method is considered best practice and why?
Here is a cut down module example from my code written in two ways.
Option 1:
var Helper = function() {};
Helper.latin_map = {"Á":"A","Ă":"A","Ắ":"A","Ặ":"A","Ằ":"A"};
Helper.prototype.urlise = function(orgString){
var lower = orgString.toLowerCase();
var latinised = lower.replace(/[^A-Za-z0-9\[\] ]/g, function(a) {
return Helper.latin_map[a] || a;
});
return latinised.replace(/\s+/g, '-')
}
module.exports = new Helper();
Option 2:
var latin_map = {"Á":"A","Ă":"A","Ắ":"A","Ặ":"A","Ằ":"A"};
module.exports = {
urlise : function(orgString){
var lower = orgString.toLowerCase();
var latinised = lower.replace(/[^A-Za-z0-9\[\] ]/g, function(a) {
return latin_map[a] || a;
});
return latinised.replace(/\s+/g, '-')
}
}
This is quite a simple example, but I will be extending this to provide several accessible functions within the same module, so before I allow things to get too complicated. I thought I would seek some advice on which approach is considered best practice.
Upvotes: 1
Views: 1615
Reputation: 664513
I have seen a number of structures using
exports
,module.exports
and even prototype, and it has left me wondering which method is considered best practice and why?
Things which had a .prototype
were constructor functions, and the module exported them as a class to be instantiated.
Exporting normal objects (as literals usually) or even extending the by-default-empty exports
object is used when you want to export a "singleton" object with static properties, a "namespace" so to say.
module.exports = new Helper()
This is almost always wrong. The Helper
is totally unnecessary, and typically even objectionable.
You should go with your Option 2. If you really did export only a single function you might consider module.exports = function urlise(orgString){…}
, but to export several functions accessible on the module your Option 2 is exactly the pattern to use.
Upvotes: 3
Reputation: 146034
Option 2 is better. You don't need constructor functions and OO instances unless you plan to do real OO programming where you create many instances and each has different data associated with it. This code works better as a simple function.
Upvotes: 2