类(class) 的继承

实现一个学生类

const Student = class {
    constructor(name, age, sex, score) {
        this.name = name
        this.age = age
        this.sex = sex
        this.score = score
    }
    info() {
        console.log(`${this.name} ${this.sex} ${this.age}  本次考试成绩${this.score}`)
    }
}

const stu1 = new Student('Tom', '男', '13', 100)
stu1.info()  // Tom 13 男  本次考试成绩100
const stu2 = new Student('Jimy', '女', '12', 100)
stu2.info()  // Jimy 12 女  本次考试成绩100


创建一个老师类:

const Teacher = class {
    constructor(name, age, sex, subject){
        this.name = name
        this.age = age
        this.sex = sex
        this.subject = subject
    }
    info(){
        console.log(`${this.name} ${this.sex} ${this.age}  教授科目:${this.subject}`)
    }
}
//实例化
const t1 = new Teacher('王阳明','男',(2023-1472),'国学')
t1.info()   // 王阳明 551 男  教授科目:国学

比较两个类可以发现它们在construct中存在相同的属性,我们可以提取公共类,通过关键字extends、super继承,具体如下:

const Person = class {
    constructor(name, age, sex) {
        this.name = name
        this.age = age
        this.sex = sex
    }
}

改造Studen 和Teacher类:

class Student1 extends Person {
    constructor(name, age, sex, score) {
        super(name, age, sex)  // 通过super(),用于继承父类
        this.score = score
    }
    info() {
        console.log(`${this.name} ${this.sex} ${this.age}  本次考试成绩${this.score}`)
    }
}

class Teacher1 extends Person {

    constructor(name, age, sex, subject) {
        super(name, age, sex)
        this.subject = subject
    }
    info() {
        console.log(`${this.name} ${this.sex} ${this.age}  教授科目:${this.subject}`)
    }
}

const student1 = new Student1('章超', '男', '15', 120)
const t2 = new Teacher1('王阳明', '男', (2023 - 1472), '理学')

student1.info() // 章超 15 男  本次考试成绩120
t2.info() // 王阳明 551 男  教授科目:理学


在看下面这段代码,

class humen extends Person{
    humenMessage() {
        console.log(`人类:${this.name} ${this.sex} ${this.age} `)
    }
}

// 实例化
const h = new humen('张三','男',20)
h.humenMessage()  // 人类:张三 20 男 

由此可见,如果继承父类且不需要新增自己的属性值,那么不需要重新指定constructor(){}, 因为在声明之时,系统已经默认生成了一个。

posted @ 2023-08-24 14:12  禺心  阅读(37)  评论(0)    收藏  举报