7、类class

typescritp对类的支持可谓是更加丰富 除了ES6 ES7 已经有的内容还添加了一些新的内容

7.1、面向对象的基础术语

  • 类(class):定义了一切事物的抽象特点
  • 对象(Object):类的实例
  • 面向对象(oop)的三大特征:封装 继承 多态

// 创建以一个类

class Animal {

// 定义构造函数

constructor(name) {

this.name = name

}

// 定义方法

run() {

return `${this.name} is running`

}

}

const snake = new Animal('lily')

console.log(snake.run())

 

// 继承

// 新定义的Dog继承了Animal

class Dog extends Animal {

bark() {

return `${this.name} is barking`

}

}

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

// 多态
class Cat extends Animal {
      // 创建静态属性 - 可直接调用
      static categories = ['mammal']
      cosntructor(name) {
             super(name)  // super重写构造函数
             console.log(this.name)
      }
      run() {
             return 'Meow, ' + super.run()
      }
}
const maomao = new Cat('maomao')
console.log(maomao.run())

 

7.2、TypeScript 中的类

  • Public:修饰的属性或方法是共有的
  • Private:修饰的属性或方法是私有的

// 创建以一个类

class Animal {

// 定义构造函数

constructor(name) {

this.name = name

}

// 定义方法

// 使用Private修饰 外部不可访问

private run() {

return `${this.name} is running`

}

}

const snake = new Animal('lily')

// 此时snake.run() 会报错

console.log(snake.run())

 

// 继承

class Dog extends Animal {

bark() {

return `${this.name} is barking`

}

}

const xiaobao = new Dog('xiaobao')
// 此时xiaobao.run() 也会报错
console.log(xiaobao.run())
console.log(xiaobao.bark())
  • Protected:修饰的属性或者方法是受保护的
// 创建以一个类

class Animal {

// 定义构造函数

constructor(name) {

this.name = name

}

// 定义方法

// 使用Protected修饰 外部不可访问 但是自己的子类可以访问

protected run() {

return `${this.name} is running`

}

}

const snake = new Animal('lily')

// 此时snake.run() 会报错

console.log(snake.run())

 

// 继承

class Dog extends Animal {

bark() {

return `${this.name} is barking`

}

}

const xiaobao = new Dog('xiaobao')
// 此时xiaobao.run() 不会报错
console.log(xiaobao.run())
console.log(xiaobao.bark())
    • readonly:修饰的属性或者方法只能读不能写
posted @ 2021-02-10 14:04  史小坑  阅读(48)  评论(0编辑  收藏  举报