简体   繁体   English

JavaScript导出类,而不仅仅是在索引文件中引用它们

[英]Javascript export class instead of just referencing them in index file

Why would I write separate classes in separate files, just to need to reference them in a central file main.js 为什么我要在单独的文件中编写单独的类,而只需要在中央文件main.js中引用它们

import Class1 from "./Class1.js";
import Class2 from "./Class2.js";
export default {
  Class1,
  Class2
};

and then reference that central file in index file 然后在索引文件中引用该中央文件

<script src="main.js"></script>

instead of just reference them all in index file, which is simpler 而不是只在索引文件中引用它们,这更简单

<script src="Class1.js"></script>
<script src="Class2.js"></script>

in both cases I can create instances: 在这两种情况下,我都可以创建实例:

const class1 = new Class1();
const class2 = new Class2();

Why is the first approach better? 为什么第一种方法更好?

It's depends on you need. 这取决于您的需要。 For example, in the main file you need to operate with two classes then you have to import them. 例如,在主文件中,您需要使用两个类进行操作,然后必须将它们导入。 But, if the two classes does not have anything in common is better import each one when is needed. 但是,如果两个类没有共同点,最好在需要时导入每个类。 In the last example, if you just need to work with one class and you the first approach ( import them in main.js ) you're loading unnecessary files and for instance using unnecessary resources. 在最后一个示例中,如果只需要使用一个类,并且第一种方法( import them in main.js ),则正在加载不必要的文件,例如使用不必要的资源。

Its for better code maintainability. 它具有更好的代码可维护性。

Lets, suppose you have 100 files, which used different classes. 让我们假设您有100个文件,它们使用了不同的类。

If we want to add new class to these 100 files, you need to edit them all. 如果要向这100个文件中添加新类,则需要全部编辑。 But if you have main.js, you just need to update 1 file only. 但是,如果您拥有main.js,则只需更新1个文件。

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

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