和public类似,protected 修饰符权限比public权限要严格一点,一旦属性和方法设置了protected权限,那么属性和方法只能在类本身和子类当中使用,不能在类之外使用。

    1. class User {
    2. // protected 权限 受保护的权限
    3. protected name: string;
    4. protected age: number;
    5. constructor(name: string, age: number) {
    6. this.name = name;
    7. this.age = age;
    8. }
    9. protected info(): string {
    10. return `我的姓名是:${this.name},我的年纪是${this.age}`;
    11. }
    12. protected run() {
    13. return this.info();
    14. }
    15. }
    16. // Person extends User
    17. class Person extends User {
    18. constructor(name: string, age: number) {
    19. super(name, age);
    20. }
    21. demo() {
    22. // 调用父类中的方法 -- 父类中的方法 可以在子类中使用
    23. return this.run();
    24. }
    25. }
    26. const p1 = new Person('root', 30);
    27. console.log( p1.demo() );

    父类User中的属性和方法权限都设置为了受保护的级别(protected),处于protected级别的属性和方法,只能在自己类本身使用和子类中使用,类的外部不能使用。

    image.png