什么是 JavaScript 嵌套函数?

javascriptweb developmentfront end technology

JavaScript 1.2 允许函数定义嵌套在其他函数中。但有一个限制,即函数定义不能出现在循环或条件语句中。这些对函数定义的限制仅适用于带有 function 语句的函数声明。

示例

您可以尝试运行以下代码来了解如何实现 JavaScript 嵌套函数 −

<html>
   <head>
      <script>
         function hypotenuse(a, b) {
            function square(x) { return x*x; }
            return Math.sqrt(square(a) + square(b));
         }
         function secondFunction(){
            var result;
            result = hypotenuse(3,4);
            document.write ( result );
         }
      </script>
   </head>
   
   <body>
      <p>Click the following button to call the function</p>
      <form>
         <input type = "button" onclick = "secondFunction()" value = "Find Hypotenuse">
      </form>
   </body>
</html>

相关文章