文章82
标签28
分类8

TypeScript 类的声明和使用

类是对象具体事物的一个抽象,对象是类的具体表现

类的声明和使用

类的命名规则:首字母大写,驼峰命名法

// 示例
class SearchInfo {
  name: string
  price: number
  constructor (name:string, price:number) {
    this.name = name
    this.price = price
  }
  say () {
    console.log('Welcome')
  }
}

let goods:SearchInfo = new SearchInfo ('苹果', 24)
console.log(goods)

goods.say()
// 输出
SearchInfo { name: '苹果', price: 24 }
Welcome

类的修饰符

  • public 公共的

  • protected 受保护的:只能在类及其子类中访问

  • private 私有的:只能在类中访问

  • readonly 只读

// 定义一个类
class SearchPeople {
  // 定义属性
  public sex: string
  protected name: string
  private age: number
  // constructor 是一种用于创建和初始化class创建的对象的特殊方法
  public constructor(sex: string, name: string, age: number) {
    this.sex = sex
    this.name = name
    this.age = age
  }
  // 定义一个sayHello方法
  public sayHello () {
    console.log('Welcome to my World')
  }
  // 定义一个sayBye方法
  protected sayBye () {
    console.log('See u again')
  }
}
// 实例化类
let people1:SearchPeople = new SearchPeople('男', '尼古拉斯赵四', 28)
console.log(people1)

console.log(people1.sex)
people1.sayHello()

class SearchBook {
  public readonly name:string = '世界百科书'
}

let book:SearchBook = new SearchBook()
// book.name = '百科世界书' 会报错,提示 name 为只读属性

类的继承和重写

类的继承用关键字 extends

需要注意的是 TypeScript 只能单重继承,不能多重继承

class MyInfo {
  public name:string
  public age:string
  public skill:string
  constructor (name:string, age:string, skill:string) {
    this.name = name
    this.age = age
    this.skill = skill
  }
  public interest () {
    console.log('唱、跳、rap、篮球')
  }
}

let MySelf:MyInfo = new MyInfo('绪锋', '24', '坤?')
MySelf.interest()

// extends 继承
class MyInfoChild extends MyInfo {
  public looks = 'handsome'
  public smart () {
    console.log('我非常聪明')
  }
  // 重写
  public interest () {
    // super 它在这里表示父类的构造函数,用来新建父类的this对象。
    super.interest()
    console.log('我不想要唱、跳、rap、篮球了')
  }
}

let Child:MyInfoChild = new MyInfoChild('绪锋的子集', '18', 'Double Kun')
Child.smart()
Child.interest()

类的命名空间

为了区分相同名字的类名,我们采用以下的命名空间

namespace SearchStar {
  export class Dipper {
    public name:string = '北斗星之一'
    say () {
      console.log('我是天枢')
    }
  }
}

namespace SearchStar2 {
  export class Dipper {
    public name:string = '北斗星之二'
    say () {
      console.log('我是玉衡')
    }
  }
}

let star1:SearchStar.Dipper = new SearchStar.Dipper()

let star2:SearchStar2.Dipper = new SearchStar2.Dipper()

star1.say()

star2.say()

接口知识

关键字 interface ,可选参数用

interface SearchFruits {
  name: string
  sweetness: string
  mouthfeel?: Boolean
}

let mySearchFruits:SearchFruits = {
  name: '西瓜',
  sweetness: '✨✨✨',
  mouthfeel: true
}

console.log(mySearchFruits)


interface SearchVegetables {
  // 定义两个参数 理想中和现实中的
  (ideal: string, reality:string): boolean
}

let mySearchVegetables:SearchVegetables = function(ideal: string, reality:string):boolean{
  let flag = ideal.search(reality)
  return (flag != -1)
}

console.log(mySearchVegetables('补VC,美味的','美味的'))