public 默认修饰符

    1. class Animal {
    2. public name: string;
    3. constructor(name: string) {
    4. this.name = name
    5. }
    6. run() {
    7. return `${this.name} is running`
    8. }
    9. }
    10. const snake = new Animal('lily')
    11. console.log(snake.run())
    12. snake.name = 'lucy'
    13. console.log(snake.run())

    private 修饰符:子类不可访问属性

    1. class Animal {
    2. private name: string;
    3. constructor(name: string) {
    4. this.name = name
    5. }
    6. run() {
    7. return `${this.name} is running`
    8. }
    9. }
    10. const snake = new Animal('lily')
    11. console.log(snake.run())
    12. class Dog extends Animal {
    13. bark() {
    14. return `${this.name} is barking` // 子类不可访问
    15. }
    16. }

    protected 修饰符:子类可以访问属性

    1. class Animal {
    2. protected name: string;
    3. constructor(name: string) {
    4. this.name = name
    5. }
    6. run() {
    7. return `${this.name} is running`
    8. }
    9. }
    10. const snake = new Animal('lily')
    11. console.log(snake.run())
    12. class Dog extends Animal {
    13. bark() {
    14. return `${this.name} is barking`
    15. }
    16. }

    readonly 修饰符
    只可读取属性,不可更改

    1. class Animal {
    2. readonly name: string;
    3. constructor(name: string) {
    4. this.name = name
    5. }
    6. run() {
    7. return `${this.name} is running`
    8. }
    9. }
    10. const snake = new Animal('lily')
    11. console.log(snake.run())
    12. snake.name = 'kip' // 报错

    static 修饰符

    1. class Animal {
    2. readonly name: string;
    3. static categoies: string[] = ['mammal', 'bird'];
    4. constructor(name: string) {
    5. this.name = name
    6. }
    7. run() {
    8. return `${this.name} is running`
    9. }
    10. }
    11. const snake = new Animal('lily')
    12. console.log(snake.run())
    13. console.log(Animal.categoies)