简体   繁体   English

在JavaScript中,使用模块或类更好吗?

[英]In JavaScript is it better to use modules or Classes?

In ES6 one can export a class in a module or just export functions as per usual. 在ES6中,可以按常规将class导出到模块中,也可以仅导出函数。 Is one or the other better? 一个或另一个更好吗?

My though is its if one wants a more functional look and feel go with exporting functions where as a more OOP approach would be to export a class. 我的想法是,如果希望导出功能具有更实用的外观和感觉,那么作为一种更多的OOP方法将是导出类。

The point of a Class in ES6 is to be able to create objects (instances) by calling the constructor and for those objects to have properties and methods that operate on those properties. ES6中Class的重点是能够通过调用构造函数来创建对象(实例),并使这些对象具有属性和对这些属性进行操作的方法。

So, if you're creating a module that intends to expose a way to create new objects that have methods and properties, then by all means expose a constructor or a factory function that can be called to create objects of the desired type. 因此,如果您要创建一个旨在提供一种方法来创建具有方法和属性的新对象的模块,则必须公开一种可以调用的构造函数或工厂函数来创建所需类型的对象。

But, if all you want to share from the module is some functions that can each be used by themselves, then there's really no reason to use the ES6 class because exporting a plain object with several functions as properties is perfectly acceptable for just sharing some functions that can be called independently. 但是,如果您要与模块共享的只是一些可以自己使用的功能,那么实际上没有理由使用ES6类,因为导出具有多个功能的纯对象作为属性对于共享某些功能是完全可以接受的可以独立调用。

So, the answer is that it depends upon what you're trying to share from the module. 因此,答案是它取决于您要从模块共享的内容。

You could, of course, also export a Class with a bunch of static methods, but that offers no particular advantage over just exporting a plain object with functions as properties so there's no particular reason to use an ES6 class for that (other than a syntax preference within the module). 当然,您也可以导出带有一堆静态方法的Class,但是与仅导出具有函数作为属性的普通对象相比,这没有什么特别的优势,因此没有特别的理由为此使用ES6类(语法除外)模块中的首选项)。

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

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