TypeScript类的继承以及修饰符

  • TS中可以通过extends继承类,这种方法同ES6中的extends
class People{
    // 属性
    name:string;
    public age:number;
    // 构造方法
    constructor(name:string, age:number) {
        this.name = name;
        this.age = age;
    }
    // 函数方法
    tell() {
        return this.name + ' ' + this.age;
    }
}
//设置P继承自People类
class P extends People{
    school:string;
    constructor(school:string) {
        // super要放在this前
        super('Tracy', 26);
        this.school = school;
    }
    tell() {
        return this.name + ' ' + this.age + ' ' + this.school;
    }
}
// 创建实例
var perl = new P('清华大学');
console.log(perl.tell());
  • TS中有prrivate和public两个修饰符
  • 如果在属性前面加上private则代表属性为私有的,子类中无法访问,强行访问会编译失败
class People{
    name:string;
    // 属性私有
    private age:number;
    constructor(name:string, age:number) {
        this.name = name;
        this.age = age;
    }
    tell() {
        return this.name + ' ' + this.age;
    }
}
//设置P继承自People类
class P extends People{
    school:string;
    constructor(school:string) {
        // super要放在this前
        super('Tracy', 26);
        this.school = school;
    }
    tell() {
        // age属性为私有,编译将会报错
        return this.name + ' ' + this.age + ' ' + this.school;
    }
}
// 创建实例
var perl = new P('清华大学');
console.log(perl.tell());
  • public则表示属性公有,在子类中可以访问

猜你喜欢

转载自blog.csdn.net/weixin_42604536/article/details/86421681
今日推荐