天天看点

TypeScript 函数中的 this 参数

从 TypeScript 2.0 开始,在函数和方法中我们可以声明

this

的类型,实际使用起来也很简单,比如:

function sayHello(this: void) {
  // this: void:表示在函数体内不允许使用this
}           

复制

在上面的 sayHello 函数中,

this

参数是伪参数,它位于函数参数列表的第一位。为什么说

this

参数是伪参数呢?因为以上的 sayHello 函数经过编译后,并不会生成实际的参数,该函数编译成 ES5 后的代码如下:

function sayHello() {
  // this: void:表示在函数体内不允许使用this
}           

复制

那么在实际开发中,

this

参数有什么用呢?下面我们来详细介绍一下

this

参数的一些应用场景。

一、未使用 this 参数

class Rectangle {
  private w: number;
  private h: number;

  constructor(w: number, h: number) {
    this.w = w;
    this.h = h;
  }

  getArea() {
    return () => {
      return this.w * this.h;
    };
  }
}           

复制

以上代码中,我们定义了一个

Rectangle

长方形类,该类中包含了两个私有的 w 和 h 属性,分别表示长方形的宽度和高度,此外还有一个

getArea

方法用于获取长方形的面积。在

getArea

方法中我们没有使用

this

参数,此时

this

的类型是 this,如下图所示:

TypeScript 函数中的 this 参数

二、使用 this 参数

class Rectangle {
  private w: number;
  private h: number;

  constructor(w: number, h: number) {
    this.w = w;
    this.h = h;
  }

  getArea(this: Rectangle) {
    return () => {
      return this.w * this.h;
    };
  }
}           

复制

与前面定义的

Rectangle

长方形类不同,在

getArea

方法中,我们使用了

this

参数,之后

this

的类型是

Rectangle

类型,如下图所示:

TypeScript 函数中的 this 参数

Rectangle

长方形类

getArea

方法中的

this

入参只是作为一个形式上的参数,供 TypeScript 做静态检查时使用,编译后并不会生成实际的入参。

三、禁止使用 this

有些时候,我们希望在方法中,禁止用户使用

this

。针对这种需求,你可以设置 this 参数的类型为

void

class Rectangle {
  private w: number;
  private h: number;

  constructor(w: number, h: number) {
    this.w = w;
    this.h = h;
  }

  getArea(this: void) {
    return () => {
      return this.w * this.h;
    };
  }
}           

复制

以上代码会提示以下异常:

Property 'w' does not exist on type 'void'.
Property 'h' does not exist on type 'void'.           

复制

四、回调函数中 this

前端开发者日常经常需要跟回调函数打交道,比如在页面中监听用户的点击事件,然后执行对应的处理函数,具体示例如下:

const button = document.querySelector("button");
// ?. -> TS 3.7引入的可选链
button?.addEventListener("click", handleClick);

function handleClick() {
  console.log("Clicked!");
  // 'this' implicitly has type 'any' because it does not have a type annotation.
  this.removeEventListener("click", handleClick);
}           

复制

对于以上代码,TypeScript 编译器会有以下错误提示:

this

隐式具有

any

类型,这是因为它没有类型注解。为了解决这个问题,我们就可以显式指定

this

参数的类型:

const button = document.querySelector("button");
button?.addEventListener("click", handleClick);

function handleClick(this: HTMLElement) {
  console.log("Clicked!");
  this.removeEventListener("click", handleClick);
}           

复制

除此之外,TypeScript 2.0 还增加了一个新的编译选项:

--noImplicitThis

,表示当 this 表达式值为 any 类型的时候,生成一个错误信息。

五、参考资源

  • function-this-parameter
  • typescriptlang - typescript-2-0