I am using NodeJS and going to write some utility functions. I think of two options here.
The first one is the traditional approach, i.e.
module.exports = {
random: () => Math.random(),
};
And the second option is to use ES6 class with static methods, e.g.
class MyMath {
static random() {
return Math.random();
}
}
module.exports = MyMath;
From programming/unit testing's perspective which one is better? Or they are pretty much the same because ES6 class essentially is a syntactic sugar?
Update: Thanks for the people who commented. I saw those questions asking class static method v.s. instance method, or prototype methods v.s. object method but mine is more like class static method v.s. Object method.
Using static-only classes as namespaces in JavaScript is the remnant of languages where a class is the only available entity. Modules already act as namespaces.
In case singleton object is needed, object literal should be used:
module.exports = {
random: () => Math.random(),
};
There's already exports
object that can be used:
exports.random = () => Math.random();
Or with ES modules:
export const random = () => Math.random();
With the class
syntax you might give more than you really intended, it is a constructor that can be invoked with new
, while with the object literal syntax you give a non-function object. As that is really what you want to expose, go for that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With