创建学生对象和教师对象并输出学生和教师相关信息(使用ES6新写法)
时间: 2023-08-09 08:09:32 浏览: 65
可以使用ES6中的class语法来创建学生和教师的对象。
下面是一个示例代码:
```javascript
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
introduce() {
console.log(`My name is ${this.name} and I'm ${this.age} years old.`);
}
}
class Student extends Person {
constructor(name, age, grade) {
super(name, age);
this.grade = grade;
}
introduce() {
console.log(`I am a student. ${super.introduce()} My grade is ${this.grade}.`);
}
}
class Teacher extends Person {
constructor(name, age, subject) {
super(name, age);
this.subject = subject;
}
introduce() {
console.log(`I am a teacher. ${super.introduce()} My subject is ${this.subject}.`);
}
}
const student = new Student("Tom", 18, 12);
student.introduce(); // 输出:I am a student. My name is Tom and I'm 18 years old. My grade is 12.
const teacher = new Teacher("Alice", 35, "Math");
teacher.introduce(); // 输出:I am a teacher. My name is Alice and I'm 35 years old. My subject is Math.
```
在这个示例中,我们定义了一个`Person`类,它有一个构造函数和一个介绍方法。然后我们定义了一个`Student`类和一个`Teacher`类,它们都继承了`Person`类。`Student`类有一个额外的`grade`属性,`Teacher`类有一个额外的`subject`属性。它们都重写了`introduce()`方法,以输出与它们相关的信息。最后,我们创建了一个学生对象和一个教师对象,并调用它们的`introduce()`方法。