用js创建一个Person类,Student类需要继承Person类的内容,并创建一个‘班级’数组存储Student类的对象
时间: 2023-05-27 22:02:25 浏览: 107
```javascript
// 创建Person类
class Person {
constructor(name, age, gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
}
// 创建Student类并继承Person类
class Student extends Person {
constructor(name, age, gender, school, grade) {
super(name, age, gender);
this.school = school;
this.grade = grade;
}
}
// 创建一个班级数组
const classArray = [];
// 创建几个Student对象并加入班级数组
const stu1 = new Student('Tom', 18, 'male', '高中一年级', '一班');
const stu2 = new Student('Mary', 17, 'female', '高中二年级', '二班');
const stu3 = new Student('Lucas', 16, 'male', '高中三年级', '三班');
classArray.push(stu1, stu2, stu3);
console.log(classArray);
```
相关问题
可以用JS编写一个person类,student类需要继承person类的内容然后创建一个班级数组储存student类的对象
以下是使用JS编写一个person类和student类,并创建班级数组:
```
// 定义person类
class person {
constructor(name, age) {
this.name = name;
this.age = age;
}
// 定义一个sayHi方法
sayHi() {
console.log("Hi, my name is " + this.name);
}
}
// 定义student类继承person类
class student extends person {
constructor(name, age, grade) {
super(name, age); // 调用父类构造函数并传入参数
this.grade = grade;
}
// 定义一个sayGrade方法
sayGrade() {
console.log("My grade is " + this.grade);
}
}
// 创建班级数组,存储student类的对象
let classList = [
new student("Amy", 14, 8),
new student("Bob", 15, 9),
new student("Cathy", 13, 7)
];
// 调用对象的方法
classList[0].sayHi(); // 输出 "Hi, my name is Amy"
classList[1].sayGrade(); // 输出 "My grade is 9"
```
用JavaScript创建一个Person类,Student类需要继承Person类的内容,并创建一个‘班级’数组存储Student类的对象
```
// 定义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.
```