欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

typescript——类的定义 继承 修饰符

程序员文章站 2022-07-03 23:18:11
...

类的定义

class Person {
  name: string // 属性

  constructor (n: string) { // 构造函数 实例化类时候触发的方法
    this.name = n
  }

  run (): void { // 方法
    console.log((this.name))
  }
}

let p = new Person('bob')
p.run()
class Person {
  name: string

  constructor (name: string) {
    this.name = name
  }

  getName (): string {
    console.log(this.name)
    return this.name
  }

  setName (name: string): void {
    this.name = name
  }
}

let p = new Person('bob')
p.getName() // bob
p.setName('lucy')
p.getName() // lucy

继承 extends super

class Person {
  name: string

  constructor (name: string) {
    this.name = name
  }

  run (): void {
    console.log(`${this.name} is running`)
  }
}

let p = new Person('tom')
p.run() // tom is running

// 继承
class Child extends Person {
  friend: string

  constructor (name: string, friend: string) {
    super(name)
    this.friend = friend
  }

  work () {
    console.log(`${this.name} is working`)
  }

  run () { // 重写父类方法
    console.log(`${this.friend} is my best friend`)
  }
}

let p1 = new Child('lucy', 'john')
p1.run() // john is my best friend
p1.work() // lucy is working

修饰符

public:公有,在类里面、子类、类外面都可以访问
protected:保护类型,在类里面、子类里面都可以访问,在类外部无法访问
private:私有,在类里面可以访问,子类、类外部都无法访问

属性如果不加修饰符,默认就是 public

class Person {
  public name1: string
  protected name2: string
  private name3: string

  constructor (json: any) {
    this.name1 = json.name1
    this.name2 = json.name2
    this.name3 = json.name3
  }

  run (): void {
    console.log(`1-1:${this.name1} 1-2:${this.name2} 1-3:${this.name3}`)
  }
}

let p = new Person({ name1: 'bob1', name2: 'tom1', name3: 'lucy1' })
p.run() // tom is running
// console.log(p.name1, p.name2, p.name3) // name2 name3 在 typescript 中编译报错

class Child extends Person {
  constructor (json: any) {
    super(json)
  }

  run (): void {
    // name3 在 typescript 中编译报错
    console.log(`2-1:${this.name1} 2-2:${this.name2} 2-3:${this.name3}`)
  }
}

let p1 = new Child({ name1: 'bob2', name2: 'tom2', name3: 'lucy2' })
p1.run()