[英]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.