Menu
CoddyTech

将类组织到模块中

本课属于 Coddy JavaScript 学习旅程的“面向对象编程”单元。第 30 课,共 56 课。

项目越来越大时,把所有类都放在一个文件里会变得很乱。想象一下,一个文件里有 10 个类,这样很难查找和维护代码。

我们已经学习了如何使用模块组织代码,包括导出和导入函数与变量。类的逻辑和语法也一样!你可以从一个文件中导出类,再将它们导入另一个文件,就像之前处理函数那样。

让我们练习如何将类整理到模块中,让代码保持整洁且易于管理。 

例如:

工作原理:

文件 1:furniture-base.js(导出基类)

export class Furniture {
 constructor(material) {
   this.material = material;
 }
 
 describe() {
   return `${this.material} furniture`;
 }
}

文件 2:chair.js(导入并扩展)

import { Furniture } from './furniture-base.js';
export class Chair extends Furniture {
 constructor(material, legs) {
   super(material);
   this.legs = legs;
 }
 
 sit() {
   return "Sitting comfortably";
 }
}

文件 3:main.js(把所有内容组合起来使用)

import { Chair } from './chair.js';
import { Table } from './table.js';
const myChair = new Chair("wood", 4);
const myTable = new Table("glass", "round");
console.log(myChair.describe());  // "wood furniture"
console.log(myTable.describe());  // "glass furniture"
challenge icon

挑战

你有一个按模块组织的电子产品商店系统。Laptop 和 Smartphone 类在不同的文件中创建,但需要让其他文件也能使用它们。

你的任务:

  1. 导出这些类(使用命名导出,而不是默认导出):
    • 在 laptop.js 中:添加 export,让其他文件可以使用 Laptop 类
    • 在 smartphone.js 中:添加 export,让其他文件可以使用 Smartphone 类
  2. 在 main.js 中导入这些类:
    • 从 laptop.js 导入 Laptop 类
    • 从 smartphone.js 导入 Smartphone 类

亲手试试

// TODO: 从 laptop.js 导入 Laptop 类

// TODO: 从 smartphone.js 导入 Smartphone 类


const myLaptop = new Laptop();
const myPhone = new Smartphone();

console.log(myLaptop.type);      // 输出:“laptop”
console.log(myPhone.type);       // 输出:“smartphone”
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向对象编程中的所有课

自己练习: JavaScript 在线编译器