说一下 ts 中的class

类示例

1、基础

class Star {
  uname: string
  uage: number
  constructor(uname: string, uage: number) {
    this.uname = uname
    this.uage = uage
  }
  sing() {
    console.log(this.uname + '开始唱歌了啦啦啦啦啦啦啦啦啦啦')
  }
  say(name: string, age: number) {
    console.log('我叫:' + name, '我今年' + age + '岁了')
  }
}

let ldh = new Star('刘华', 18)
console.log('类=', ldh)
ldh.sing()
ldh.say('华仔', 218)

2、抽象类

抽象类和其他类区别不大,只是不能用来创建对象。抽象类专门用来被继承,子类必须重写父类(抽象类)的抽象方法。抽象类中可以添加抽象方法,抽象方法只能定义在抽象类中,子类必须对抽象方法进行重写。

abstract class Per {
  name: string
  age: number
  constructor(name: string, age: number) {
    this.name = name
    this.age = age
  }
  abstract sing(): void
  abstract sum(a: number, b: number): number
  abstract play(type: string): void
}

class Fhcq extends Per {
  n: string
  a: number
  num1: number
  num2: number
  constructor(name: string, age: number, num1: number, num2: number) {
    super(name, age)
    this.n = name
    this.a = age
    this.num1 = num1
    this.num2 = num2
  }
  sing(): void {
    console.log('子类必须对抽象方法进行重写')
  }
  sum(a: number, b: number): number {
    return a + b
  }
  play(type: string) {
    console.log('晚秋啊type=', type)
  }
}

let dnf = new Fhcq('凤凰传奇', 20, 1, 2)
console.log('dnf=', dnf)
dnf.sing()
console.log(dnf.sum(9, 9))
dnf.play('乒乓球')

你可能感兴趣的:(typeScript,typescript)