繁体   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