Javascript 简明教程
JavaScript - Modules
What is a Module?
JavaScript 中的 module 是包含 JavaScript 代码或脚本的单个文件。与其将整个应用程序的代码添加到单个文件中,我们可以分解代码并为具有相同功能的代码创建单独的文件。
A module in JavaScript is a single file containing a JavaScript code or script. Rather than adding the code for the whole application in a single file, we can break down the code and create separate files for the code having the same functionalities.
简而言之,模块包含执行特定任务的代码。它可以包含变量、函数、类等。
In short, the module contains the code to perform the specific task. It can contain variables, functions, classes, etc.
当应用程序的大小增长时,代码中的行数也会增长。即使是实时应用程序也包含数百万行代码。现在,想想如果开发人员只有一个包含数百万行代码的文件。他们能够正确管理它吗?简单的回答是否定的。在此,使用模块开始发挥作用。
When the size of the application grows, number of lines in the code also grows. Even real-time applications contain millions of lines of code. Now, think about if developers have only a single file containing millions of lines of code. Are they able to manage it properly? The simple answer is no. Here, using the module comes into the picture.
Syntax
用户可以遵循以下语法导出和导入模块。
Users can follow the syntax below to export and import the modules.
export function func_name(parameters) {
// function code
}
import {func_name} from filename
在上述语法中, export 关键字用于从模块导出函数, import 关键字用于从模块导入函数。
In the above syntax, the export keyword is used to export the function from the module, and the import keyword is used to import the function from the module.
Example
Filename: mul.js
Filename: mul.js
在下面的代码中,我们在’mul.js’文件中定义了’mul()’函数,它接受两个整数作为参数并返回它们的乘积。此外,我们在’function’关键字前使用了’export’关键字,以便从模块导出函数。
In the code below, we defined the 'mul()’ function in the 'mul.js' file, which takes two integers as a parameter and returns the multiplication of them. Also, we used the 'export' keyword before the 'function' keyword to export the function from the module.
// exporting mul() function
export function mul(a, b) {
return a * b;
}
Filename: test.html
Filename: test.html