1. // public 定义类的变量默认就是公共的,继承的子类可以通过this来访问
    2. // private 定义类的私有属性,只能在内部访问
    3. class Person {
    4. private name: string = ""
    5. getName() {
    6. return this.name
    7. }
    8. setName(newName) {
    9. this.name = newName
    10. }
    11. }
    12. const p = new Person()
    13. console.log(p.getName())
    14. p.setName('xbj')
    15. // protected: 在类的内部和子类中可以访问,在外面就访问不到了
    16. class Person {
    17. protected name: string
    18. constructor(name: string) {
    19. this.name = name
    20. }
    21. }
    22. class Student extends Person {
    23. constructor(name: string, age: number){
    24. super(name)
    25. }
    26. getName() {
    27. return this.name
    28. }
    29. }