Javascript-nested-functions

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

JavaScript-入れ子関数

JavaScript 1.2より前では、関数定義はトップレベルのグローバルコードでのみ許可されていましたが、JavaScript 1.2では関数定義を他の関数内にネストすることもできます。 それでも、関数定義がループまたは条件内に表示されないという制限があります。 関数定義に関するこれらの制限は、関数ステートメントを使用した関数宣言にのみ適用されます。

次の章で後述するように、関数リテラル(JavaScript 1.2で導入された別の機能)はJavaScript式内に現れる可能性があります。つまり、 if や他のステートメント内に現れる可能性があります。

次の例を試して、ネストされた関数を実装する方法を学習してください。

<html>
   <head>
      <script type = "text/javascript">
         <!--
            function hypotenuse(a, b) {
               function square(x) { return x*x; }
               return Math.sqrt(square(a) + square(b));
            }
            function secondFunction() {
               var result;
               result = hypotenuse(1,2);
               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>

出力