2
1

Arrow function っていつ使う?

Posted at

結論

メソッド内でコールバック関数を書くときは、Arrow function を使うと便利です。

理由

Arrow function の this は、暗黙的な引数として this を受け取らず、関数が定義されたスコープの this を参照します。
この特性により、Arrow function を使うと単純に this を使うことができます。

例えば、次のコードを見てください:

class Timer {
  constructor() {
    this.seconds = 0;
  }

  start() {
    setInterval(function () {
      this.seconds++;
      console.log(this.seconds);
    }, 1000);
  }
}

const timer = new Timer();
timer.start(); // ここでの this は Timer インスタンスを指していないため、エラーになります。

上記の例では、通常の function を使うと thissetInterval のコンテキストを指すため、this.seconds は定義されていないというエラーになります。

一方、Arrow function を使うと次のように動作します:

class Timer {
  constructor() {
    this.seconds = 0;
  }

  start() {
    setInterval(() => {
      this.seconds++;
      console.log(this.seconds);
    }, 1000);
  }
}

const timer = new Timer();
timer.start(); // ここでの this は Timer インスタンスを指すため、秒数が正しくカウントされます。

このように、Arrow function を使うと、this が Timer インスタンスを正しく指すため、コールバック関数内でも簡単に this を扱うことができます。

メソッド内でコールバック関数を書くとき以外は?

複雑なthisのバインディングや、プロトタイプチェーンを使うときを除いて、通常の function と Arrow function のどちらを使っても問題なさそうです。

個人的には、上記の通りthisの扱いが簡単になるのでArrow functionに統一しても良いかなと思っています。

現場に合わせておくのが無難かもですね。

参考

https://jsprimer.net/basic/function-this/

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1