Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 class static method vs function

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.

like image 979
Eric Xin Zhang Avatar asked Mar 08 '19 05:03

Eric Xin Zhang


2 Answers

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();
like image 153
Estus Flask Avatar answered Sep 18 '22 12:09

Estus Flask


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.

like image 44
trincot Avatar answered Sep 22 '22 12:09

trincot