2022/9/8 TypeScript

# 初步认识

通过使用类的方式来定义一个对象

 interface Iperson{
    firstName:string,
    lastName:string
  }

  class Person{
    // 定义公共的字段
    firstName:string//姓氏
    lastName:string//名字
    fullName:string//名字
    constructor(firstName:string,lastName:string){
      this.firstName=firstName
      this.lastName=lastName
      this.fullName=this.firstName+'-'+this.lastName
    }
  }
  // 实例化对象
  const person=new Person('卧龙','凤雏')
  
  function showFullName(person:Iperson){
    return person.firstName+'-'+person.lastName
  }
  console.log(showFullName(person))

实例化的对象的时候通过类中constructor构建函数来复制公共字段中的变量,类本身也是一个对象

# 继承

继承属于类与类之间的关系,发生继承就会出现子类和父类之间的关系 子类又叫派生类,父类也叫基类,例如:我特别帅,我的儿子继承啦我的颜值也特比帅

// 父类
  class Person{
    name:string
    age:number
    constructor(name:string,age:number){
      this.name=name
      this.age=age
    }
    sayHi(str:string){
      console.log(`我是${this.name},你是${str}`)
    }
  }
// 子类
class Student extends Person{
  constructor(name:string,age:number){
    super(name,age)
  }
  sayHi(){
    console.log('我是子类的方法')
    super.sayHi('帅哥')
  }
}
//实例化Person
const person = new Person('路飞',21)
person.sayHi('索隆')
//实例化Student
const stu = new Student('乔巴',28)
stu.sayHi()

# 公共、私有、受保护修饰符

  • public
    • public是类默认的属性,公共的意思,任何地方都可以访问类中的成员
  • private
    • 类中的成员如果用他来修饰,外部是无法访问这个成员属性的,子类也不行
  • protected
    • 类中的成员如果用他来修饰,外部是无法访问这个成员属性的,子类可以

# readonly只读修饰符

readonly队成员修饰后,该成员就不能再外部被随意修改

class Person{
  readonly name:string
  constructor(name:string){
    this.name=name
  }
  sayHi(){
    //   this.name='罗宾'   !!! 报错
    console.log(`我是${this.name}`)
  }
}

const person:Person=new Person('娜美')
//   person.name='罗宾'   !!! 报错

# 存取器

class Person{
  firstName:string
  lastName:string
  constructor(firstName:string,lastName:string){
    this.firstName=firstName
    this.lastName=lastName
  }
  get fullNmae(){
    return this.firstName+'_'+this.lastName
  }
  set fullName(val){
    let names=val.split('_')
    this.firstName=names[0]
    this.lastName=names[1]
  }
}

const person:Person=new Person('蒙奇D','路飞')
// 获取该成员属性
console.log(person.fullName)
// 设置该成员属性
person.fullName='罗罗诺亚_索隆'

# 静态成员

通过static修饰符的属性或者方法称作为静态成员属性

静态成员属性只能通过类名这种语法来调用

class Person{c 
  name:string='弗兰奇'
  constructor(){
  }
  seyHi(){
    console.log('海侠-甚平')
  }
}
// 错误演示
const person=new Person()
console.log(person.name)  // !!!错误

// 正确演示   不用创建实例对象就能调用 
console.log(person.name)
Person.name='乔巴'
Person.seyHi()
Last Updated: 2022/9/27 17:24:24