typescript 中的 this 類型


typescript中,this 也是一種類型,一個計算器的例子:

class Counter{
  constructor(public count:number = 0){}

  add(value:number){
    this.count += value
    return this
  }

  subtract(value:number){
    this.count -= value
    return this
  }
}

let counter = new Counter(10)
console.log(counter.count) // 10
counter.add(2).subtract(3) 
console.log(counter.count) // 9

這里 this 指的是實例對象,每個方法都返回 this 類型時,我們就可以通過鏈式調用的形式來使用這些方法。

 

上面的類使用了 this 類型,你可以繼承它,新的類可以直接使用之前的方法,不需要做任何的改變。

class PowerCounter extends Counter{
  constructor(public count:number){
    super(count)
  }

  pow(value:number){
    this.count = this.count ** value
    return this
  }
}

let powcounter = new PowerCounter(2)
powcounter
.pow(3)
.add(3)
.subtract(1)

console.log(powcounter.count) // 10

PowerCounter 繼承了 Counter,本身只定義了 pow 這個實例方法,但是因為返回了  this 類型,所以可以使用父類中的方法。

 

在對象中,屬性值可以是一個函數,函數內訪問 this,默認情況下是對這個對象的引用,this 類型也就是這個對象的字面量類型:

const info = {
  name:'Tom',
  getName(){
    return this.name // Tom 這里的 this 類型是 {name:string, getName():string}
  }
}

如果顯式指定了 this 類型,那么 this 的類型就改變了:

const info = {
  name:'Tom',
  getName(this:{age:number}){
    this // 這里的 this 類型就是 {age: number}
  }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM