var、let 和 const 的區別以及暫時性死區

面試時候碰到這個問題,多數的回答都是比起 var,後兩者不會變量提升,並且生效於塊級作用域。但這還不夠。

先上結論:let,var,const,三者都會變量提升。

  • var 是創建和初始化的過程都提升了,所以提前訪問得到 undefined。
  • let 只是創建過程提升,提前訪問報錯 xx is not defined,這其實是暫時性死區的表現
  • const、class 和 let 相似,只是 const 無法修改變量
  • function 的創建、初始化、賦值都提升了,所以提前訪問則沒啥問題

爲什麼說 let 也有變量提升呢?

看個例子

let x = 'outer value';
(function() {
  console.log(x); // 輸出 outer value
}());

let y = 'outer value';
(function() {
  console.log(y); // Uncaught ReferenceError: Cannot access 'y' before initialization
  let y = 'inner value';
}());

依照上面的例子,x 能被輸出,而想輸出 y 報錯,就能證實內層的 y 存在變量提升,只是提前訪問會報錯。這其實是暫時性死區的表現。

暫時性死區 Temporal dead zone 在 MDN-let 中有着解釋

Unlike variables declared with var, which will start with the value undefined, let variables are not initialized until their definition is evaluated. Accessing the variable before the initialization results in a ReferenceError. The variable is in a "temporal dead zone" from the start of the block until the initialization is processed.

含義就是:只要一進入當前作用域,所要使用的變量就已經存在了,但是不可獲取,只有等到聲明變量的那一行代碼出現,纔可以獲取和使用該變量。

圖片出自 csdn-辰辰沉沉大辰沉-let/const 的變量提升與暫時性死區

參考

csdn-辰辰沉沉大辰沉-let/const 的變量提升與暫時性死區

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章