【发布时间】:2022-10-01 23:56:00
【问题描述】:
我对 JavaScript 很陌生,来自 Java 背景。我只是在玩 NodeJS (\"type\": \"module\") Express 框架,但在两种用 JS 编写方法的方法之间徘徊。
以下是示例(在线检查相机)。
类型 1:
main.js
const method1 = () => {
...
method2();
...
};
const method2 = () => {
// this is not exported, so it works as a private method and won\'t be accessible in other JS files
...
};
.
.
.
// likewise there can be many other methods here
export { method1 }; // export other methods as well
然后,我可以在任何其他 JS 文件中使用method1(不能使用method2,因为它没有导出),如下所示:
test.js
import { method1 } from \'./main.js\';
method1();
类型 2:
main.js
class Main {
method1() {
...
method2();
...
}
#method2() {
// this is a private method, so won\'t be accessible outside of this class
...
}
// likewise other methods here
}
const main = new Main();
export default main;
然后,我可以在任何其他 JS 文件中使用这个类实例,如下所示:
test.js
import main from \'./main.js\';
main.method1();
我想知道这两者有什么区别,什么时候用哪个,哪个更好。
-
这是基于意见的。即使存在一些细微的客观差异(例如给定的 JS 环境是否支持私有方法语法),也无法明确回答。这个问题基本上归结为你喜欢OOP还是FP的风格封装。
-
我了解 OOP,但什么是 FP 风格?
-
函数式编程。在您的第一个示例中,您使用模块系统从导入该文件的代码中封装“method2”。这在允许您定义独立函数和/或缺乏面向对象的语言中更为典型。
-
啊,明白了,所以你的意思是说,以上两种类型基本相同,可以根据个人喜好使用(WRT JS)?
-
@JigneshM.Khatri 您的 sn-ps 之间的最大区别在于对象。您可以多次实例化
new Main(),并且可以分别在每个对象中保持状态。如果您需要这样做,请使用class。如果您不需要具有不同数据的多个实例,并且不需要保持状态,则不应使用classes 并使用简单的无状态静态函数。
标签: javascript node.js ecmascript-6