当前位置:   article > 正文

TS的访问修饰符有哪些

TS的访问修饰符有哪些

如果你和我一样是从强类型语言(如C++、C#、Java)转过来的,相信你会一眼就知道是什么

public(默认) - 全部可访问

protected - 自己和派生类可访问

private - 只有自己可访问

废话不多说,上代码:

class Person {
    public name: string = '';
    protected age: number;
    private girlfriend: string = '小雨';

    constructor(name: string, age: number) { 
        this.name = name; this.age = age; 
        console.log(this.girlfriend); // 可以访问私有属性
    }
}

class Employee extends Person {
    constructor(name: string, age: number) { super(name, age); }
    getInfo() {
        console.log(`姓名:${this.name}`);
        console.log(`年龄:${this.age}`);
        // console.log(`女朋友:${this.girlfriend}`); // 报错,因为女朋友是私有的
    }
}

const employee = new Employee('张三', 18); 
employee.getInfo();
employee.name = '李四'; // 可以修改公共属性
// employee.age = 20; // 报错,因为age是受保护的
// employee.girlfriend = '小红'; // 报错,因为girlfriend是私有的
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

// class属性的另一种写法
class Person2 {
    constructor(public name: string, protected age: number, private girlfriend: string = '小丽') {}
}
  • 1
  • 2
  • 3
  • 4

拓展:面向对象的三要素

封装(privite、protected)、继承、多态(例如函数重载)
本文第一句话,会强类型语言的朋友我相信都知道。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小舞很执着/article/detail/877450
推荐阅读
相关标签
  

闽ICP备14008679号