gpt4 book ai didi

javascript - ES6 类静态方法 vs 函数

转载 作者:搜寻专家 更新时间:2023-10-31 23:39:42 25 4
gpt4 key购买 nike

我正在使用 NodeJS 并打算编写一些实用函数。我在这里想到两个选择。

第一个是传统的方法,即

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

第二种选择是使用带有静态方法的 ES6 类,例如

class MyMath {
static random() {
return Math.random();
}
}
module.exports = MyMath;

从编程/单元测试的 Angular 来看,哪个更好?或者它们几乎相同,因为 ES6 类本质上是一种语法糖?

更新:感谢发表评论的人。我看到那些问类静态方法与类静态方法的问题。实例方法,或原型(prototype)方法 vs.对象方法,但我的更像是类静态方法 vs.对象方法。

最佳答案

在 JavaScript 中使用仅静态类作为命名空间是语言的残余,其中类是唯一可用的实体。模块已经充当命名空间。

如果需要单例对象,应该使用对象字面量:

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

已经有可以使用的exports对象:

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

或者使用 ES 模块:

export const random = () => Math.random();

关于javascript - ES6 类静态方法 vs 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55057465/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com