技術向上

プログラミングの学び、気になるテクノロジーやビジネストレンドを発信

アロー関数式とthis【TypeScript】

TypeScriptでもアロー関数式を使うことができます。

function helloA(): () => string {
    return () => {return "Hello, world"};
}

function helloA(): () => string {
    return () => "Hello, world";
}


class定義のメンバメソッドについて、アロー関数式と通常のfunction式とで、thisの参照先が異なります。

class Sample {
  name: string;
  constructor() {
      this.name = "who";
  }

  helloA(): () => string {
    return () => "Hello, " + this.name;
  }

  helloB(): () => string {
    return function() {return  "Hello, " + this.name};    // thisの型を指定していない場合、any型になる旨のエラーが出る
  }
}


アロー関数式ではthisが定義元のclass内を参照しますが、function式の場合、実行時には実行時のスコープを参照してしまいます。コンパイル後のJavascriptファイルを見ると、アロー関数式の場合はthisスコープを変数「_this」に保存しています。

Functions · TypeScript

Typed 'this' in object literal methods by ahejlsberg · Pull Request #14141 · Microsoft/TypeScript · GitHub