JavaScript 中的閉包和巢狀函式之間有什麼區別?


JavaScript 閉包

在 JavaScript 中,所有函式在呼叫時都會像閉包一樣工作。閉包是一種函式,它在宣告作用域中使用該作用域。而不是在它被呼叫的作用域中。

下面是一個例子

即時演示

<!DOCTYPEhtml>
<html>
   <body>
      <h2>JavaScriptClosures</h2>
         <script>
            varp = 20;
            functiona(){
               var p = 40;
               b(function(){
                  alert(p);
            });
         }
         functionb(f){
            var p = 60;
            f();
         }
         a();
      </script>
   </body>
</html>

JavaScript 巢狀函式

JavaScript 1.2 允許函式定義巢狀在其他函式中。但是,有一個限制:函式定義不能出現在迴圈或條件中。函式宣告中使用 function 語句時適用這些函式定義的限制。

示例

你可以嘗試執行以下示例來學習如何實現巢狀函式

即時演示

<html>
   <head>
      <script>
         <!--
            functionhypotenuse(a,b) {
               functionsquare(x){returnx*x;}
               returnMath.sqrt(square(a)+square(b));
            }
           
            functionsecondFunction() {
               varresult;
               result=hypotenuse(5,4);
               document.write(result );
            }
         //-->
      </script>
   </head>
   <body>
      <p>Clickthe following button to call the function</p>
      <form>
         <inputtype="button"onclick="secondFunction()"value="CallFunction">
      </form>
      <p>Usedifferent parameters inside the function and then try...</p>
   </body>
</html>

更新於: 2020 年 1 月 9 日

882 次瀏覽

開啟你的 職業生涯

完成該課程獲得認證

立即開始
廣告
© . All rights reserved.