javascript 関数の引数に関数を利用する

javascript 関数の引数に関数を利用する

javascriptで関数の引数に関数を利用するサンプルコードを掲載してます。ブラウザはchromeを使用しています。

環境

  • OS windows10 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 104.0.5112.101

関数の引数に関数を利用

「javascript」では関数の引数に、関数を使用することが可能です。

<input id="btn" type="button" value="ボタン"/>

<script>

'use strict';

document.getElementById('btn').onclick = function () {
  hoge(foo) // foo関数を引数に使用
}

function hoge(func) {
  func()
}

function foo() {
  console.log("fooを実行しました")
}

</script>

実行結果

また、以下のコードを、

document.getElementById('btn').onclick = function(){
    hoge(foo)
}

document.getElementByIdの省略化、アロー関数を使用して、簡潔に記述することもできます。

btn.onclick = () =>{	
    hoge(foo)
}

サンプルコード

以下は、
ボタンをクリックすると、関数を引数に、別の関数を実行してテキストを表示する
サンプルコードとなります。

※cssには「tailwind」を使用して、アロー関数で関数は定義してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet">
</head>

<script>  
  
  const hoge = (f) => {
    f()    
  }

  const foo = () => {

    result.innerHTML = "hoge関数内でfoo関数を実行しました";
    
  }

  window.onload = () => {

    btn.onclick = () => { hoge(foo) };

  }

</script>

<body>
  <div class="container mx-auto my-56 w-64 px-4">

    <div id="sample" class="flex flex-col justify-center">

      <p id="result" class="bg-blue-500 text-white py-2 px-8 rounded-full mb-3 mt-4"></p>

      <button id="btn"
        class="py-2 px-4 bg-green-600 text-white font-semibold rounded-lg shadow-md">
        foo関数実行
      </button>

    </div>

  </div>
</body>

</html>

テキストが表示されていることが確認できます。