0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Javascript】戻り値が関数である関数(学習ノート)

Posted at

初めに

関数を戻り値にする関数について学習した内容のoutput用記事です。

※内容に間違いなどがある場合はご指摘をよろしくお願いします。
※こちらの記事はあくまでも個人で学習した内容のoutputとしての記事になります。

試してみる

次のようにcalculatesという関数の戻り値が関数である場合を考えてみます。

const calculates = function (a, b) {
  return function (c) {
    console.log(a + b * c);
  }
}

calculatesに引数を1と2を渡し、変数exampleに格納します。この時、exampleはcという引数を取る関数になります。

const example = calculates(1, 2);
//exampleはfunction(c)と同様
example(3);
example(4);

スクリーンショット 2021-06-09 11.03.34.png
これはfunction(a,b)の戻り値はfunction(c)になるので連続して書くこともできます。

calculates(1,2)(3);
calculates(1,2)(4);

結果は先ほどと同じです。
スクリーンショット 2021-06-09 11.03.34.png

アロー関数を使えば、次のようにさらに短く書くことも可能です。

const calAttr = (a, b) => (c) => console.log(a + b * c);
calAttr(1,2)(3);
calAttr(1,2)(4);

参考サイト

0
0
2

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?