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