简体   繁体   English

为什么在隐藏变量时不能引用变量?

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

Why does block A result in a ReferenceError? 为什么阻止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';

}

This prevents one from shadowing a variable with one of its properties. 这样可以防止人用其属性之一遮盖变量。

Because const variables are hoisted , and you are trying to access it in its own temporal dead zone. 由于const变量已被提升 ,因此您试图在其自己的临时死区中对其进行访问。 There are three ways of solving this: 有三种解决方法:

  • Just use a different variable name, don't shadow non-global variables. 只需使用其他变量名,不要隐藏非全局变量。 It's confusing. 令人困惑。
  • Don't use const , don't make a local scope - just reassign the variable inside the block. 不要使用const ,不要创建局部作用域-只需在块内重新分配变量即可。 This solution might not be applicable everywhere. 此解决方案可能不适用于任何地方。
  • Use an IIFE: 使用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