TypeScript中类的修饰符

类成员的修饰符

  • public:公有属性,可以在类内部访问,可以在实例访问,可以在子类访问
  • private:私有属性,外部不能访问,只在类内部访问
  • protected:受保护的,自身和子类访问
  • static:静态,只能是类本身访问,不可在类内部访问,不可在子类访问,不可在实例访问

class A1 {
  
  public x: number;

  protected y: string;

  private z: boolean;

  static w: number = 100

  constructor(x: number, y:string) {
    this.x = x;

    this.y = y;
    
    this.z = true;
  }

  public test(): void {
    // 访问
    console.log('this.x ==>', this.x);
    
    // 访问y
    console.log('this.y ==>', this.y);
    
    // 访问z
    console.log('this.z ==>', this.z);

    // 访问w
    // console.log('this.w ==>',this.w);
    
  }

}

class A2 extends A1{

  public getData(): void{
    console.log('A2 this.x ==>',this.x);
    console.log('A2 this.y ==>', this.y);
    // console.log('A2 this.z ==>',this.z);
  }
}

let a1: A1 = new A1(2,'hello');
console.log('a1 ==>',a1);

a1.test();
// console.log('a1.y ==>',a1.y);
// console.log('a1.z ==>',a1.z);

let a2: A2 = new A2(8, 'world');
console.log('a2 ==>',a2);
a2.getData()

// console.log('a2.y ==>',a2.y);

// 访问A1类的静态属性w
console.log('A1.w ==>',A1.w);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端小渣渣丿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值