class实现继承

59 阅读1分钟
class Person {
    constructor(name) {
        this.name = name;
    }
    drink() {
        console.log('喝水')
    }
}

class Teacher extends Person {//继承Person, 
    constructor(name, subject){
        //this.name = name;
        super(name);//super()执行父类的构造函数, 把所需参数传进去即可
        this.subject = subject;
    }
    
    teach() {
        console.log(`我是${this.name}, 是${this.subject}老师`)
    }
}
const teacher = new Teacher('小孟', '英语')
teacher.teach();//'我是小孟,是英语老师'
teacher.drink();//'喝水'

class Student extends Person {//继承Person, 
    constructor(name, score){
        //this.name = name;
        super(name);//super()执行父类的构造函数, 把所需参数传进去即可
        this.socre = socre;
    }
    
    introduce() {
        console.log(`我是${this.name}, 考了${this.score}分`)
    }
}
const student = new Student('小马', '0')
student.introduce();//'我是小马,考了0分'
student.drink();//'喝水'