简体   繁体   English

ES6类静态方法vs函数

[英]ES6 class static method vs function

I am using NodeJS and going to write some utility functions. 我正在使用NodeJS并编写一些实用程序函数。 I think of two options here. 我想到两个选择。

The first one is the traditional approach, ie 第一个是传统方法,即

module.exports = {
    random: () => Math.random(),
};

And the second option is to use ES6 class with static methods, eg 第二种选择是使用ES6类和静态方法,例如

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? 或者它们几乎相同,因为ES6类本质上是一个语法糖?

Update: Thanks for the people who commented. 更新:感谢评论的人。 I saw those questions asking class static method vs instance method, or prototype methods vs object method but mine is more like class static method vs Object method. 我看到了那些问题类静态方法与实例方法,或者原型方法与对象方法的问题,但我更像是类静态方法与对象方法。

Using static-only classes as namespaces in JavaScript is the remnant of languages where a class is the only available entity. 在JavaScript中使用仅静态类作为名称空间是语言的残余,其中类是唯一可用的实体。 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对象:

exports.random = () => Math.random();

Or with ES modules: 或者使用ES模块:

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. 使用class语法,您可能提供的内容超出了您的预期,它是一个可以使用new调用的构造函数,而使用对象文字语法可以提供非函数对象。 As that is really what you want to expose, go for that. 因为这是你想要公开的,所以去吧。

Classes with only static methods are the same as a bunch of isolated functions. 只有静态方法的类与一堆独立的函数相同。 In this case you probably don't need to use it. 在这种情况下,您可能不需要使用它。 As for unit tests it is pretty much the same since classes with only static methods does not differ that much from functions. 至于单元测试,它几乎是相同的,因为只有静态方法的类与函数的差别不大。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM