首页 > 解决方案 > 在 javascript 中创建一个 util 类

问题描述

我想为我的反应应用程序创建一个实用程序类。util 类应该是静态类,据我所知不能实例化。那么,在 javascript 中创建 util 类的正确方法是什么,以及我们如何使它成为静态的?

标签: javascript

解决方案


您可以定义一个只包含static方法的类,它可能如下所示:

class Util {

  static helper1 () {/* */}
  static helper2 () {/* */}

}

export default Util;

但是,由于您不需要实例化实用程序类的对象,因此您可能并不需要一个类,并且导出实用程序函数的简单模块将更好地满足您的需求:

const helper1 = () => {/* */};
const helper2 = () => {/* */};

export default {
  helper1,
  helper2
};

推荐阅读