菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
221
0

typescript 中的 this 类型

原创
05/13 14:22
阅读数 61043

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}
  }
}

 

发表评论

0/200
221 点赞
0 评论
收藏
为你推荐 换一批