javascript new Functionを使って関数を定義する

javascript new Functionを使って関数を定義する

javascriptで、new Functionを使って関数を定義するサンプルコードを記述してます。

環境

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

new Function使い方

構文は以下のようになります。

const func = new Function(引数, 引数,... ,'処理');

以下は「new Function」を使用して関数を作成した例となります。

const func = new Function('x', 'y', 'return x + y');

console.log(func(2, 3));
// 5

引数は、カンマでまとめて記述することも可能です。

const func = new Function('x, y', 'return x + y;');

console.log(func(2,3));
// 5

また、new Functionを使用すれば、以下のように処理を変数として利用することができます

const str = 'alert("hello");'

const func = new Function(str);

console.log(func());

実行結果

newは、省略することもできます。

const str = 'alert("hello");'

const func = Function(str);

console.log(func());

サンプルコード

以下は、
「実行」ボタンをクリックすると「new Function」を使用して関数を実行してhtmlの要素のテキストを変更する
サンプルコードとなります。

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

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

<script>

  const hoge = new Function('result.innerHTML = "実行されました";');

  window.onload = () => {
    // クリックイベントを登録
    btn.onclick = () => { hoge(); }; // document.getElementById('btn');を省略    
  }

</script>

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

    <div class="flex justify-center">
      <p id="result" class="bg-purple-500 text-white py-2 px-4 rounded-full mb-3 mt-4">結果</p>
    </div>

    <div class="flex justify-center">

      <button id="btn" type="button"
        class="mt-5 bg-transparent border border-pink-500 hover:border-pink-300 text-pink-500 hover:text-pink-300 font-bold py-2 px-4 rounded-full">
        実行
      </button>
    </div>
  </div>

</body>

</html>

変更されていることが確認できます。