TypeScript(五):类 Class

  • 类(Class):定义了一切事物的抽象特点,如:汽车、动物等等

  • 对象:类的实例(奥迪、狗等)

  • 面向对象(OOP)三大特性:封装、继承、多态

1 类的实例

  • 基础实例
class Animal {
  name: string;
  constructor(name: string) {
    this.name = name
  }
  run() {
    return `${this.name} is running`
  }
}

const snake = new Animal('lily')
console.log(snake.run()) // lily is running

  • 继承
class Animal {
  name: string;
  constructor(name: string) {
    this.name = name
  }
  run() {
    return `${this.name} is running`
  }
}

// 继承 Animal,拥有 Animal 的属性和方法
class Dog extends Animal {
  bark() {
    return `${this.name} is barking`
  }
}

const xiaobao = new Dog('xiaobao')
xiaobao.run()
xiaobao.bark()

  • 重写父类方法
class Animal {
  name: string;
  constructor(name: string) {
    this.name = name
  }
  run() {
    return `${this.name} is running`
  }
}

class Cat extends Animal {
  constructor(name) { // 如果使用 constructor,必须使用 super,重写父类的构造方法
    super(name)
    console.log(this.name)
  }
  run() { // 重写
    return 'Meow, ' + super.run() 
  }
}

const maomao = new Cat('maomao')
maomao.run() // Meow, maomao is running

2 类的修饰符

类的修饰符有 public、protect、private

  • public
    属性和方法默认就是 public
class Animal {
  public name: string;
  constructor(name: string) {
    this.name = name
  }
  run() {
    return `${this.name} is running`
  }
}

const snake = new Animal('lily')
console.log(snake.name)
  • private
    只有在类内部使用
class Animal {
  private name: string;
  constructor(name: string) {
    this.name = name
  }
  run() {
    return `${this.name} is running`
  }
}

const snake = new Animal('lily')
console.log(snake.name) // error
  • protect,只有在类本身和子类可以使用

  • 只读属性,只能读,不可以写

class Animal {
 readonly name: string;
  constructor(name: string) {
    this.name = name
  }
  run() {
    return `${this.name} is running`
  }
}

const snake = new Animal('lily')
console.log(snake.name) // OK

snake.name = '11112' // error,只读属性
  • 静态属性和方法,类直接调用,无需创建实例
class Animal {
  name: string;
  static categoies: string[] = ['mammal', 'bird']
  static isAnimal(a) {
    return a instanceof Animal
  }
  constructor(name: string) {
    this.name = name
  }
  run() {
    return `${this.name} is running`
  }
}

console.log(Animal.categoies)

const snake = new Animal('lily')
console.log(Animal.isAnimal(snake))

你可能感兴趣的:(TypeScript(五):类 Class)