视频位置 TypeScript快速梳理_下篇 0:00:32

class Person {
    // 属性声明
    name: string
    age: number

    // 构造器 构造函数
    constructor(name: string, age: number) {
        this.name = name
        this.age = age
    }

    // ⽅法
    speak() {
        console.log(`我叫:${this.name},今年${this.age}岁`)
    }
}

// Person类的实例
const p1 = new Person('张三', 18)
console.log(p1)
p1.speak()

继承

假如创建 Student类,继承自 Person类。
例如:

class Student extends Person {
    //在原来 Person类的基础上增加属性 grade 年级。
    grade: string

    // 构造器 Person类的前个参数不能丢,然后加上需要增加的 grade属性
    constructor(name: string, age: number, grade: string) {
        //super()调用父类的构造器,同时将 name,age 传递过去。
        super(name, age)

        this.grade = grade
    }

    //如果对父类的speak()方法不满意,可以在此重写(覆盖父类的该方法)
    //override 不写也不会报错误,但是从语法严谨的角度,应该写上:表示要重写父类的该方法
    // 备注本例中若Student类不需要额外的属性,Student的构造器可以省略
    // 重写从⽗类继承的⽅法
    override speak() {
        console.log(`我是学⽣,我叫:${this.name},今年${this.age}岁,在读${this.grade} 年级`,)
    }

    // ⼦类⾃⼰的⽅法
    study() {
        console.log(`${this.name}正在努⼒学习中...`)
    }
}

//测试: 创建一个 Student的实例对象
const s1 = new Student('李同学',16,'高三')
s1.study()
s1.speak()