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}
      }
    }
  • 相关阅读:
    7maven依赖排除
    5maven生命周期
    4maven依赖范围、依赖有效性
    3maven常用命令和配置依赖
    1maven概念作用
    6在Eclipse中创建maven和修改默认配置
    2maven下载与配置
    Class 'org.apache.tomcat.jdbc.pool.DataSource' not found
    17 alternatives to your default image viewer on Fedora
    zip压缩包解压后的文件名是乱码?
  • 原文地址:https://www.cnblogs.com/wjaaron/p/12974604.html
Copyright © 2011-2022 走看看