如何在JavaScript函式主體內部定義函式?


要實現你的目標,請使用 JavaScript 閉包。閉包是一個函式,呼叫時使用其宣告時的作用域。不是呼叫時的作用域。

示例

讓我們以你的例子為例,這是你完成任務的方法。此處, innerDisplay() 是一個 JavaScript 閉包。

Var myFunction = (function () {
   function display() {
      // 5
   };
   function innerDisplay (a) {
      if (/* some condition */ ) {
         // 1
         // 2
         display();
      }else {
         // 3
         // 4
         display();
      }
   }
   return innerDisplay;
})();

更新於: 2020 年 1 月 7 日

128 次瀏覽

開啟 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.