Javascript-function-literals

提供:Dev Guides
移動先:案内検索

JavaScript関数リテラル

JavaScript 1.2では、関数を定義する別の新しい方法である*関数リテラル*の概念が導入されています。 関数リテラルは、名前のない関数を定義する式です。

構文

  • 関数リテラル*の構文は関数ステートメントによく似ていますが、ステートメントではなく式として使用され、関数名は不要です。
<script type = "text/javascript">
   <!--
      var variablename = function(Argument List) {
         Function Body
      };
  //-->
</script>

構文的には、次のようにリテラル関数を作成しながら関数名を指定できます。

<script type = "text/javascript">
   <!--
      var variablename = function FunctionName(Argument List) {
         Function Body
      };
  //-->
</script>

しかし、この名前には意味がないので、価値はありません。

次の例を試してください。 関数リテラルの使用法を示しています。

<html>
   <head>
      <script type = "text/javascript">
         <!--
            var func = function(x,y) {
               return x*y
            };
            function secondFunction() {
               var result;
               result = func(10,20);
               document.write ( result );
            }
        //-->
      </script>
   </head>

   <body>
      <p>Click the following button to call the function</p>

      <form>
         <input type = "button" onclick = "secondFunction()" value = "Call Function">
      </form>

      <p>Use different parameters inside the function and then try...</p>
   </body>
</html>

出力