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を学ぶ―関数オブジェクトとは―

Last updated at Posted at 2021-04-18

JavaScriptでは「関数はオブジェクト」であるようです。
Javaを学習していたので、意味が分かりません…
違和感があるので、まとめてみたいと思います。

関数はオブジェクト

  • 関数⇒は何かしらの処理
  • オブジェクト⇒モノ

であると認識していますが、この2つが何故同じオブジェクトであるのでしょうか?

何となく分かりやすい料理のレシピで例えると

  • 関数⇒やること:何かを作るために、何が必要で、どんな手順で処理するか。
  • オブジェクト⇒レシピ:どんな材料で、どんな手順で何ができるか書いたもの。

こう考えるとほぼ一緒ですね。

関数をオブジェクト扱いするとどうなるか

JavaScriptではこのように「関数は処理手順を定義したオブジェクト」として扱われます。
オブジェクトなので変数に代入したり、引数として別の関数に渡したりすることが可能です。

ソースコードを見てみる

    <script>

        function add(a, b) {
            return a + b;//※ a + bというメソッドを返す
        }

        //a+bというメソッドをcalcLatorに代入する
        const calcLator = add;

        //xに2+3=5を代入する
        const x = calcLator(2, 3);

        console.log(x);//5

    </script>

上記のコードだと、***※***の位置でa+bというメソッドをオブジェクトとして扱っているので、calcLatorという変数に代入が可能という訳です。
calcLatorは計算式がはいっているので、calcLator(2, 3);とすると2+3をしてくれます。

因みに無名関数(関数名を指定しない)書き方はこんな感じです。

<script>
        //無名関数
        //a/bをそのままcalcLatorに入れたvar
        const calcLator = function (a, b) {
            return a / b;
        }
        //xに3/2=5を代入する
        const z = calcLator(3, 2);

        console.log(z);//1.5
</script>

まとめ

関数オブジェクトのポイントは***「関数オブジェクト単体で考えるのではなく、呼び出し側とペアで考えること」
関数オブジェクトは単体では意味がなく、利用する呼び出し側があって初めて機能します。

「関数もオブジェクト」が分かってきました。

参考:https://book.impress.co.jp/books/1115101084

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