簡體   English   中英

為什么在隱藏變量時不能引用變量?

[英]Why can you not refer to a variable when shadowing it?

為什么阻止A會導致ReferenceError?

const something = 'something';

console.log ();

try {

    // Block A
    {

        const something = something;

    }

} catch (e) { console.log(e); }

console.log ();

// Block B
{

    const something = 'somethingElse';

}

這樣可以防止人用其屬性之一遮蓋變量。

由於const變量已被提升 ,因此您試圖在其自己的臨時死區中對其進行訪問。 有三種解決方法:

  • 只需使用其他變量名,不要隱藏非全局變量。 令人困惑。
  • 不要使用const ,不要創建局部作用域-只需在塊內重新分配變量即可。 此解決方案可能不適用於任何地方。
  • 使用IIFE:

     const something = 'something'; (function(something) { // ^^^^^^^^^ inner scope … }(something)); //^^^^^^^^^ outer scope 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM