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>

更新於: 09-01-2020

882 次瀏覽

開啟你的職業生涯

透過完成該課程獲得認證

開始
廣告
© . All rights reserved.