TS中private protected public readonly的区别

在TypeScript中,privateprotectedpublicreadonly是用于类成员(属性和方法)访问控制和可变性的关键字。以下是它们各自的作用和区别:

Public

  • public是默认的访问修饰符,如果未指定,则成员默认为public
  • public成员可以在类的外部被访问和修改。
    class Person {
      public name: string; // public是默认的,所以可以省略public关键字
    
      constructor(name: string) {
        this.name = name;
      }
    
      public getName(): string {
        return this.name;
      }
    }
    
    const person = new Person('Alice');
    console.log(person.name); // 可以访问
    person.name = 'Bob'; // 可以修改
    

    Private

  • private成员只能在类内部被访问和修改,不能在类的外部被访问,即使是子类也不能访问。
  • 子类不能覆盖private成员。
    class Person {
      private name: string;
    
      constructor(name: string) {
        this.name = name;
      }
    
      public getName(): string {
        return this.name;
      }
    }
    
    const person = new Person('Alice');
    // console.log(person.name); // 错误:属性“name”为私有属性,只能在类“Person”中访问。
    

    Protected

  • protected成员可以在类内部和继承该类的子类中被访问和修改。
  • 子类可以覆盖protected成员。
    class Person {
      protected name: string;
    
      constructor(name: string) {
        this.name = name;
      }
    
      public getName(): string {
        return this.name;
      }
    }
    
    class Employee extends Person {
      constructor(name: string, public title: string) {
        super(name);
      }
    
      public getDetails(): string {
        return `${this.name},${this.title}`; // 可以访问protected成员
      }
    }
    
    const employee = new Employee('Alice', 'Developer');
    // console.log(employee.name); // 错误:属性“name”为受保护的属性,只能在类“Person”及其子类中访问。
    

    Readonly

  • readonly关键字用于属性,表示该属性只能在构造函数中被赋值,之后就不能再被修改。
  • readonly属性可以是publicprotectedprivate
    class Person {
      readonly name: string;
    
      constructor(name: string) {
        this.name = name;
      }
    }
    
    const person = new Person('Alice');
    console.log(person.name); // 可以访问
    // person.name = 'Bob'; // 错误:无法分配到“name”,因为它是只读属性。
    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值