private、public、protected、readonly、static

1、默认是public

自由的访问程序里定义的成员

class Parent {
    
    
  public name: string;
  constructor(theName: string) {
    
    
    this.name = theName;
  }
}
let a = new Parent("张三").name;

2、private

私有,不能在声明它的类的外部访问,如下

class Parent {
    
    
  private name: string;
  constructor(theName: string) {
    
    
    this.name = theName;
  }
}
let a = new Parent("张三").name; //属性"name"为私有属性,只能在类"Parent"中访问。

在这里插入图片描述

3、protected

受保护成员只能在类及其子类中访问,而不能在类的实例中访问

class Parent {
    
    
  protected name: string;
  constructor(theName: string) {
    
    
    this.name = theName;
  }
}
let a = new Parent("张三").name;//属性"name"受保护,只能在类"Super及其子类中访问"

在这里插入图片描述

class Parent {
    
    
  protected name: string;
  constructor(theName: string) {
    
    
    this.name = theName;
  }
}
// let a = new Parent("张三").name;
class Cat extends Parent {
    
    
  constructor(theName: string) {
    
    
    super(theName);
    this.name = '张三,'
  }
}

4、readonly修饰符

class Octopsus {
    
    
    readonly name: string;
    readonly numberOfLegs: string;
    constructor(theName: string) {
    
    
        this.name = theName
    }
}
let dad = new Octopsus('张三');
dad.name = "修改值" //无法分配到"name",因为它是只读属性。

在这里插入图片描述

5、static

类的静态成员只能通过类名来调用,二不能通过子类调用

class Octopus {
    
    
    public name: string;
    constructor(theName: string) {
    
    
        this.name = theName
    }
    static food = "fish"
}
console.log(Octopus.food)

参考文档:https://typescript.bootcss.com/classes.html

猜你喜欢

转载自blog.csdn.net/weixin_44700978/article/details/122375586
今日推荐