zoukankan      html  css  js  c++  java
  • 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}
      }
    }
  • 相关阅读:
    下载地址jquery upload file demo (C#)
    特征卷积基于3D卷积神经网络的人体行为理解(论文笔记)
    应用目录S5PV210的BL1应用
    手机音效手机测试游戏类
    metadata查询Querying Metadata
    arraynodeSorting
    functionclass[LeetCode]Path Sum II
    functionclass[LeetCode]Permutation Sequence
    exceptionfunction[LeetCode]Permutations
    exceptionfunction[LeetCode]Permutations II
  • 原文地址:https://www.cnblogs.com/wjaaron/p/12974604.html
Copyright © 2011-2022 走看看