用JavaScript创建一个Person类,Student类需要继承Person类的内容,并创建一个‘班级’数组存储Student类的对象
时间: 2023-05-27 12:02:29 浏览: 104
```
// 定义Person类
class Person {
constructor(name, age, gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
introduce() {
console.log(`Hi, I'm ${this.name}, ${this.age} years old, ${this.gender}.`);
}
}
// 定义Student类,继承Person类
class Student extends Person {
constructor(name, age, gender, grade) {
super(name, age, gender);
this.grade = grade;
}
introduce() {
console.log(`Hi, I'm ${this.name}, ${this.age} years old, ${this.gender}. I'm in grade ${this.grade}.`);
}
}
// 创建班级数组
let class1 = [];
// 添加学生信息
let student1 = new Student('Tom', 18, 'male', 10);
let student2 = new Student('Lucy', 17, 'female', 9);
let student3 = new Student('Jack', 18, 'male', 10);
class1.push(student1);
class1.push(student2);
class1.push(student3);
// 输出学生信息
for (let i = 0; i < class1.length; i++) {
class1[i].introduce();
}
```
运行结果:
```
Hi, I'm Tom, 18 years old, male. I'm in grade 10.
Hi, I'm Lucy, 17 years old, female. I'm in grade 9.
Hi, I'm Jack, 18 years old, male. I'm in grade 10.
```
阅读全文