继承
// 继承
class Person{
constructor(name){
this.name = name
}
drink(){
console.log("喝水")
}
}
// 学生类 继承了Person的name属性和drink函数
class Student extends Person{
// 构造函数
constructor(name,age){
// 调用父类的构造函数
super(name)
this.age = age
}
// 学生的自我介绍函数
studentInfo(){
console.log(`我叫${this.name},年龄${this.age}`)
}
}
const student1 = new Student("小明",18)
student1.studentInfo()
student1.drink()
console.log(`————————————————`)
// 教师类 继承了Person的name属性和drink函数
class Tearch extends Person{
// 构造函数
constructor(name,salary){
// 调用父类的构造函数
super(name)
this.salary = salary
}
// 教师的自我介绍函数
tearchInfo(){
console.log(`我叫${this.name},工资${this.salary}`)
}
}
const tearch1 = new Tearch("王二",2000)
tearch1.tearchInfo()
tearch1.drink()
使用场景:两个类中如果存在相同属性或函数的情况(name),可以创建一个父类来继承相同属性或函数
参考视频
参考地址 (转载):https://www.bilibili.com/video/BV1Q64y1v7fW?p=1&vd_source=7a9ee67ca4d1e90007c9d660ba6f04b5