JavaScript中的继承

class Student{
    constructor(name,grade) {
        this.name = name
        this.grade = grade
    }
    introduce(){
        console.log(`我是${this.name},我打了${this.grade}分`);
    }
}
let student = new Student('张三',99)

class Teacher extends Student{
    constructor(hobby) {
        super('tom', 100);
        this.hobby = hobby
    }
    sayHello(){
        console.log('我是Teacher');
    }
}
let teacher = new Teacher('basketball')
console.log(teacher);  //{ name: 'tom', grade: 100, hobby: 'basketball' }
teacher.introduce()  //我是tom,我打了100分
/*
* 一个类必须要有构造器
* 在那个introduce方法中,必须要this.xxx,才能拿到属性,因为是这个对象上才有这个属性,java中也是如此,也是this.xxx
* 在子类Teacher中,super那里就相当于给继承过来的student的构造器传参
* 还有,super必须要写,不然会报错
* 倘若super那里不传参,那么teacher就会输出{ name: undefined, grade: undefined, hobby: 'basketball' }
* 继承就相当于子类拥有父类的属性和方法,这也是继承的意义所在
* super相当于给继承过来的属性赋值
* */
posted @ 2022-06-29 11:01  朱在春  阅读(12)  评论(0编辑  收藏  举报