Reputation: 5947
{}
vs Export functionI'm developing an exercise application, I came across to the question When do I need to exports an object {}
instead of a function class?
Scenario example:
I'm building a simple authentication module
using the object style.
// file auth.js
module.exports = {
login: function() {
// code login
},
logout: function() {
// code logout
},
register: function() {
// code register
}
}
Here I'm using the anonymous function style
module.exports = function() {
return {
login: function() {
// code login
},
logout: function() {
// code logout
},
register: function() {
// code register
}
}
}
When I want to require this module I just do:
var auth = require('auth');
auth.login(); // trigger login function via object
auth().login() // trigger login function via function
It will work with both the approaches, but I'm confused to choose which fit better and why.
How do you understand in your design of a module, when is appropriate to exports, an object, anonymous function, named function to Instantiate?
Which are the difference and how the require method behave, when requiring these functions or Objects ?
Upvotes: 10
Views: 6517
Reputation: 146074
How do you understand in your design of a module, when is appropriate to exports, an object, anonymous function, named function to Instantiate?
tempConversion
module might have both cToF
and fToC
functions.var tip = require('computeTip')(18);
could store 18 in closure and return a function that would calculate 18% tip when called with a number.Here's a rule of thumb: if you export only one named function a la require('average').average(listOfNumbers)
, it's redundant, so just export the average
function directly to make it more concise. If you have more than one function you want to expose, use an object whose properties are the functions.
Which are the difference and how the require method behave, when requiring these functions or Objects ?
require
has a single behavior that accommodates each of these techniques.Upvotes: 7
Reputation: 473
In both your examples you actually return an object and not a function class. In the second case you get the object by executing the function. In order to use the function as a class you should return a function which acts as the constructor, and then instantiate with the new operator.
That being said, I would prefer an object over a class if I consider my module as a singleton, something that would be common to every file that would include it. An example would be a module that implements a common access layer to my database.
A class makes more sense if you intent to instantiate it multiple times. An example would be a specific model class for your database schema, like a User class.
Upvotes: 3