How is block scope managed in the lexical environment?

后端 未结 2 1546
广开言路
广开言路 2021-02-20 06:01

If I declare a variable in a function using var then a slot for that variable is added to the LexicalEnvironment defined by that function.



        
2条回答
  •  忘掉有多难
    2021-02-20 06:29

    function() {
      var foo; 
    }
    

    As you mentioned, foo is available in the LexicalEnvironment is global to all inner functions within that function.

    But

    function() {
      {
        let foo; // How does this affect the LexicalEnviroinment?
      }
    }
    

    Here foo is local to that block alone. It won't be visible outside that block.

    How does it affect the LexicalEnvironment ?

    If you are referencing, foo anywhere inside that block, the local let foo will override the global var foo which you've defined in that function.

    With respect to ES6,

    function example(x) {
        console.log(y); // ReferenceError: y is not defined
        if (x) {
            let y = 5;
        }
    }
    

    Variables declared with a let statement are created as bindings on the lexical environment, rather than the variable environment, of the current execution context. A change to the specification of block statements in ES6 means that each block has its own lexical environment. In the above example, a new lexical environment is created when the block (the body of the if statement) is evaluated. When the let statement is evaluated a binding is added to this lexical environment and is innaccessible from the outer lexical environment (that of the function declaration itself).

    Refer

提交回复
热议问题