TS-11 面向?qū)ο?class 下

  • 成員可見(jiàn)性:
  1. public:類外可見(jiàn)(默認(rèn)就是public),類內(nèi)及子類也都可訪問(wèn)
  2. private:僅類內(nèi)可見(jiàn),this.xxx,但類型擦除后,如果人家用js引用,還是可以訪問(wèn),因此ts提供了#var作為真正的私有屬性
  3. protected:類內(nèi)及子類可見(jiàn),類似于整個(gè)家族類可見(jiàn)
class Person {
  friend?: Person // 默認(rèn)是public
  protected gender = 'male'
  private height = 170
  public weight = 70
  #age = 20 // 真正的私有屬性(private)
  constructor(public name:string,friend?:Person){
    this.friend = friend
    this.name = name
    this.#age = 20
  }
  sayHi(){
    console.log(this.name)
  }
  getHeight(){
    console.log(this.height)
    console.log(this.name)
    console.log(this.gender)
  }
}

const p = new Person('frank')
p.sayHi()
p.getHeight()

class User extends Person{
  declare friend?: User
  constructor(name:string,friend?:User){
    super(name,friend)
  }
  test(){
    console.log(`---${this.gender}---`)
    console.log(`---${this.weight}---`)
    // 不能訪問(wèn) this.height
  }
}

const u1 = new User('mike')
u1.test()
u1.weight
// 不能訪問(wèn) u1.gender 以及 u1.height 
  • static:靜態(tài)屬性,就是類自身的屬性,類似于原型中的共有屬性的概念
class Student {
  static grade = 7  // 可修改
  static readonly tag = '' // 不能修改
}

Student.grade = 8
  • 注意點(diǎn):靜態(tài)屬性不能聲明name,因?yàn)閏lass在js中就是函數(shù)class A {}; typeof A === 'function',而所有的函數(shù)都有name屬性
  • 類和泛型
class Hash<K,V> extends Map<K,V> {
  destroy(){
    this.clear() // 繼承自Map類的方法
  }
}
  • 匿名類
  • abstract:抽象類,可以不實(shí)現(xiàn)一部分屬性。不能創(chuàng)建實(shí)例
  • 把類當(dāng)做參數(shù):
class Person {
  constructor(public name:string){}
}

function f(X:typeof Person){
  const p = new X('frank')
  console.log(p.name)
}

f(Person)

// 這不是箭頭函數(shù),箭頭函數(shù)是不能加 new 的
function f2(X: new (name:string) => Person){
  const p = new X('ricky')
  console.log(p.name)
}

f2(Person)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容