JavaScript 导出类
JavaScript 导出/导入语句适用于 JavaScript 模块的内容在另一个模块中重用的情况。
可以有许多方法来执行任务,从单个模块到模块的细节传输以及从子模块到父模块的聚合。
JavaScript 中 export
语句的类型
JavaScript 中的 export
/import
语句有两种类型。一种是命名
导出,另一种是默认
导出。
通常,在 Default
类别中导出时,我们不使用花括号来包装基元或对象。但是在 Named
导出的情况下,我们使用花括号来包装多个对象或原语。
Default
仅处理从模块导出的一项,而 Named
可以取零或多于一。
我们将需要一个文件或模块来跟进示例。我们将它们命名为 test.js
和 New.js
。
但是为了与 ES6 兼容,我们需要将模块重命名为 test.mjs
和 New.mjs
。有多种方法可以执行此转换,但这很容易。
在这里,我们将看到一个具有 Default
类别的实例和另一个具有 Named
类别的实例。让我们跳到下一节。
JavaScript 中 Default
导出的示例
在此示例中,我们将在 test.mjs
中启动一个类 User
,我们将导出该类。User
类只有最喜欢的水果的名称。
接下来,在声明类的构造函数之后,让我们进入 New.mjs
模块并导入该类。我们还将通过设置一些值来触发导出的模块工作。
让我们检查一下这个例子。
// test.mjs
export default class User {
constructor(fruit) {
this.fruit = fruit;
}
}
// New.mjs
import User from './test.mjs';
var x = new User('Mango');
console.log(x);
输出:
JavaScript 中 Named
导出的示例
我们将为此实例采用一个带有虚拟数学的函数和一个变量。因此,我们将在要导出的每个数据之前声明 export
语句。
稍后,在我们的父模块 New.mjs
中,我们将根据选择导入和修改值。此线程中提供了正式的声明性解释。
代码片段:
// test.mjs
export function square(x) {
return x * x;
}
export var y = Math.PI * 5;
// New.mjs
import {square, y} from './test.mjs';
var x = 2;
console.log(square(x));
console.log(y);
输出:
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。