TypeScript 封装 继承 多肽

今天被小学弟问到类的声明和继承感觉他没看明白.....

//人类
class People {
    //人类的共有属性
    readonly idCard: number;
    public name: string;
    public sex: string;
    protected age: number;

    constructor(idCard: number, name: string, sex: string, age: number) {
        this.idCard = idCard;
        this.name = name;
        this.sex = sex;
        this.age = age;
    }
    //类方法
    protected greet() {
        if (this.age < 18) {
            console.log("未成年人不得入内!")
        } else {
            console.log(`你好,欢迎${this.name}光临~`)
        }
    }
}

//学生
class Student extends People {
    // 学生特有的属性
    public school: string;
    readonly stuCard: number;

    constructor(idCard: number, name: string, sex: string, age: number, school: string, stuCard: number) {
        //学生继承People的共有属性
        super(idCard, name, sex, age);
        this.school = school;
        this.stuCard = stuCard;
    }

    public greet() {
        super.greet();
        console.log("学生类重写People类方法");
    }
}

//实例化
let guAiLing: Student = new Student(123, '谷爱凌', '女', 18, '美国xxx中学', 456);
guAiLing.greet();
console.log(guAiLing.name);
console.log(guAiLing.school);
//学生
class Student extends People {
    // 学生特有的属性
    // public school: string;
    // readonly stuCard: number;

    // constructor(idCard: number, name: string, sex: string, age: number, school: string, stuCard: number) {
    //     //学生继承People的共有属性
    //     super(idCard, name, sex, age);
    //     this.school = school;
    //     this.stuCard = stuCard;
    // }

    public greet() {
        super.greet();
        console.log("学生类重写People类方法");
    }
}

//实例化
let guAiLing: Student = new Student(123, '谷爱凌', '女', 18);
guAiLing.greet();
console.log(guAiLing.name);
console.log(guAiLing.sex);

如果子类不写构造函数的话typescript会自动继承父类的属性,但是实例化的时候必须带上父类的参数。



上一篇:小程序云开发入门——问卷测评小程序实战(3)


下一篇:Aistudio使用经验积累(持续更新中)