[06] JavaScript 入門 - 拉升、嚴格模式


keywords:hoisting,strict mode

拉升 ( Hoisting )

一個 var 宣告會被移到包含它的範疇 ( enclosing scope ) 的最頂端

  • 變數 ex:
      x = 5;
      console.log(x); // 5
      var x;
    
  • 函式 ex:

      abc();
    
      function abc() {
          var x = 8;
          console.log(x);
      }
      // 8
    

Tips:仰賴變數拉升並非常見的做法,函式宣告的拉升較為常見

  • 如果在無法取用某變數的範疇中試著取用該變數的值,就會擲出 ReferenceError

      function aaa(){
          console.log(x)
      }
    
      function bbb(){
          var x = 9;
          console.log(x);
      }
      aaa(); // Uncaught ReferenceError: x is not defined
    
  • 如果試著設定尚未宣告的變數,會依是否使用 strict 模式而有差異:
    • 非嚴格模式下 - 尚未宣告的變數在頂層建立了一個全域變數
        function abc(){
            a = 3; // a 並無正式宣告
            console.log(a);
        }
        abc(); // 3
        a; // 3 omg not good
      
    • 嚴格模式下 - 擲出一個錯誤( 接下來會說明 strict 模式是什麼)
       'use strict'
       function abc(){
            a = 3; // a 並無正式宣告
            console.log(a);
        }
        abc(); // Uncaught ReferenceError: a is not defined
      

嚴格模式 ( Strict Mode)

會以更嚴謹的方式來規範某些行為,strict 模式通常可以讓程式碼更容易被引擎最佳化,可以讓個別的函式或整個檔案選擇使用 strict 模式

function abc(){
  'use strict'
  // 這裡的程式碼使用 strict 模式

  function bbb(){
    // 這裡的程式碼使用 strict 模式
  }

}
// 這裡的程式碼不使用 strict 模式

strict 模式關鍵的優點是,它不允許省略 var 宣告而隱含且自動建立全域變數 ( 上方有提到 )

'use strict'
function abc(){
  a = 3;

  console.log(a);
}

abc(); // 擲出 ReferenceError : a is not defined
#hoisting #strict mode







你可能感興趣的文章

Express template engine - Handlebars 載入 使用

Express template engine - Handlebars 載入 使用

DAY29:Array.diff

DAY29:Array.diff

〈 C++學習日記 #2〉再談指標 Pointer (Part.2)

〈 C++學習日記 #2〉再談指標 Pointer (Part.2)






留言討論