大学管理系统
本课属于 Coddy JavaScript 学习旅程的“面向对象编程”单元。第 55 课,共 56 课。
挑战
在这个挑战中,我们有一个大学系统,其中包含不同类型的人(学生、教授),他们有不同的角色和行为。
1. 完成 Person 类:
- 添加
introduce()方法,返回"Hi, I'm ${name}"
2. 完成 Student 类:
- 重写
introduce(),使其返回${super.introduce()}, a ${this.major} student。示例:“Hi, I'm Alice, a Computer Science student” - 添加
addGrade(grade)方法,接收一个介于 0 和 100 之间的分数- 验证:检查分数是否介于 0 和 100 之间
- 如果有效:将分数添加到
this.grades数组中 - 如果无效:记录:
"Grade must be between 0 and 100"
3. 完成 Professor 类:
- 重写
introduce(),使其返回“Prof. ${name} from ${department}”。示例:“Prof. Smith from Computer Science”
亲手试试
import { Person } from './person.js';
import { Student } from './student.js';
import { Professor } from './professor.js';
// 创建人物
const student1 = new Student('Alice', 20, 'Computer Science');
const prof1 = new Professor('Dr. Johnson', 50, 'Mathematics');
console.log(student1.introduce()); // "Hi, I'm Alice, a Computer Science student"
console.log(prof1.introduce()) // "Prof. Dr. Johnson from Mathematics"
student1.addGrade(85);
student1.addGrade(90);
student1.addGrade(95);
console.log(`${student1.name}'s GPA: ${student1.getGPA()}`); // ~3.6
student1.addGrade(105); // 应该输出:“Grade must be between 0 and 100”面向对象编程中的所有课
8整理 OOP 代码
将类组织到模块中自己练习: JavaScript 在线编译器