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>

輸出

javascript_functions.htm
廣告