typescript中private、public、protected修饰符

1、默认为public

2、当成员被标记为private时,它就不能在声明它的类的外部访问,比如:

class Animal {
  private name: string;

  constructor(theName: string) {
    this.name = theName;
  }
}

let a = new Animal('Cat').name; //错误,‘name’是私有的

3、protected和private类似,但是,protected成员在派生类中可以访问

class Animal {
  protected name: string;

  constructor(theName: string) {
    this.name = theName;
  }
}

class Rhino extends Animal {
     constructor() {
          super('Rhino');
    }         
    getName() {
        console.log(this.name) //此处的name就是Animal类中的name
    }
}    

4、构造函数也可以被标记为protected。这意味着这个类不能再包含它的类外被实例化,但是能被继承,也就是可以在派生类中被super执行

class Animal {
    protected name: string;
    protected constructor(theName: string) {
       this.name = theName;
    }         
}

//Rhino能够继承Animal
class Rhino extends Person {
    private food: string;
    constructor(name: string, food: string) {
       super(name);
       this.food = food;    

    }    
     getFood() {
        return `${this.name} love this ${this.food}`
     }
}

let rhino = new Rhino('zhao', 'banana');

 

转载于:https://www.cnblogs.com/zhaoljblog/p/9224490.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值