微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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会自动继承父类属性,但是实例化的时候必须带上父类的参数。


                
                                 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐