简体   繁体   中英

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

Why does block A result in 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. 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. This solution might not be applicable everywhere.
  • Use an IIFE:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM