I want to create a util class for my react app. util classes should be static classes which cannot be instantiated as I know. So, what is the proper way to create a util class in javascript and how we can make it static?
I want to create a util class for my react app. util classes should be static classes which cannot be instantiated as I know. So, what is the proper way to create a util class in javascript and how we can make it static?
Share Improve this question asked Jan 26, 2019 at 18:23 Shashika VirajhShashika Virajh 9,47720 gold badges64 silver badges112 bronze badges2 Answers
Reset to default 18You can define a class that contains only static
methods, it may look something like as follows:
class Util {
static helper1 () {/* */}
static helper2 () {/* */}
}
export default Util;
However, since you don't need a possibility to instantiate an object of the utility class, chances are that you don't really need a class and a simple module that exports utility functions will suite your demand better:
const helper1 = () => {/* */};
const helper2 = () => {/* */};
export default {
helper1,
helper2
};
@anotonku's answer is almost perfect, but a little add-on to the second option - in some IDE
(it's you, VSCode
); if you wrap the function in export default
without a name, it would not be recognised as in suggestions.
And if this bothers you, just export the function directly:
export const helper1 = () => {/* */};
export const helper2 = () => {/* */};
It would work as expected.