ts 类中的修饰符

138 阅读2分钟

一、修饰符是什么

  • 修饰符:类中的 成员的修饰符,主要是描述类中的成员(属性构造方法方法)的 可访问性

  • 类中的成员都有自己的 默认修饰符 public

  • 修饰符有哪几种?

    • public公共的,任何位置都可以访问

    • private私有的,只有 自身内部可以访问,外部、子类中都无法访问该成员数据

    • protected受保护的自身内部和子类中 可以访问,外部无法访问

    • readonly: 只读,仅可在构造函数中修改

    • static静态的,修饰属性普通方法(非构造函数)

      • 修饰后被称为 静态成员
      • 静态成员 在使用时通过 类名.静态成员 这种语法来调用的,而不是通过 this实例(实例化对象)

二、通过例子来理解以上用法

1、public

外部、内部、子类内部 都可访问

// 定义一个类
class Person {
  public name: string
  constructor(name: string) {
    this.name = name
  }
  eat () {
    // 内部访问
    console.log('eat', this.name)
  }
}


// 子类
class Student extends Person {
constructor (name: string) {
super(name)
}




play () {
// 子类内部访问
console.log('play', this.name)
}
}




const person = new Person('小明')
// 内部,可访问
person.eat()
// 外部,可访问
console.log('person.name', person.name)




const stu = new Student('小红')
// 子类内部,可访问
stu.eat()
stu.play()
// 外部,可访问
console.log('stu.name', stu.name)

2、private

只有内部 可访问,外部、子类内部都不可访问

// 定义一个类
class Person {
  private name: string
  constructor(name: string) {
    this.name = name
  }
  eat () {
    // 内部访问
    console.log('eat', this.name)
  }
}
// 子类
class Student extends Person {
  constructor (name: string) {
    super(name)
  }
  play () {
    // 子类内部,不可访问
    console.log('play', this.name)
  }
}


// name 为 private 时,只有内部可访问,外部、子类内部都不可访问
const person2 = new Person('小明')
// 内部,可访问
person2.eat()
// 外部:不可访问
console.log('person2.name', person2.name)




const stu2 = new Student('小红')
// 子类内部,不可访问
stu2.eat()
stu2.play()
// 外部:不可访问
console.log('stu2.name', stu2.name)

3、protected

内部子类内部 可访问,外部不可访问

// 定义一个类
class Person {
 protected name: string
 constructor(name: string) {
   this.name = name
 }
 eat () {
   // 内部访问
   console.log('eat', this.name)
 }
}
// 子类
class Student extends Person {
 constructor (name: string) {
   super(name)
 }
 play () {
   // 子类内部, 可访问
   console.log('play', this.name)
 }
}


const person3 = new Person('小明')
// 内部,可访问
person3.eat()
// 外部:不可访问
console.log('person3.name', person3.name)




const stu3 = new Student('小红')
// 子类内部,可访问
stu3.eat()
stu3.play()
// 外部:不可访问
console.log('stu2.name', stu3.name)

4、readonly

只读,仅在 构造函数 中可以被修改

class Person {
  // 可读可写
  name: string


// 只读
readonly sex: string
readonly age: number = 16




constructor (name: string, sex: string) {
// 构造函数中,可以修改被设置为 readonly 的属性
this.name = name
this.sex = sex
this.age = 18
}




sayName () {
// 可读可写
this.name = '猪猪'
}




saySex () {
// 类中的普通方法,不能修改被设置为 readonly 的属性(编译报错)
// this.sex = '中性'
}
}

5、static

修饰 属性普通方法,使用时通过 类名 调用

class Person {
  // 普通属性
  nameOwn: string
  // 静态属性
  static gender: string = '女'


// 构造函数前不能添加 static
constructor (name: string) {
this.nameOwn = name // 访问静态属性,需要通过 【类名.属性】访问
}
// 普通方法
sayHi () {
console.log('hello你们好')
}


// 静态方法
static sayStatic () {
console.log(Person.gender)
}
}
// 实例化对象
const per = new Person('佩奇')
// 访问普通方法,通过实例
per.sayHi()
// 访问静态方法,要通过 【类名.方法】访问
Person.sayStatic()