最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Creating a util class in javascript - Stack Overflow

programmeradmin2浏览0评论

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 badges
Add a comment  | 

2 Answers 2

Reset to default 18

You 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.

发布评论

评论列表(0)

  1. 暂无评论