How is block scope managed in the lexical environment?

后端 未结 2 1580
广开言路
广开言路 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:27

    Questions like this are best be answered by looking at the spec:

    Block : { StatementList }

    1. Let oldEnv be the running execution context’s LexicalEnvironment.
    2. Let blockEnv be NewDeclarativeEnvironment(oldEnv).
    3. Perform BlockDeclarationInstantiation(StatementList, blockEnv).
    4. Set the running execution context’s LexicalEnvironment to blockEnv.
    5. Let blockValue be the result of evaluating StatementList.
    6. Set the running execution context’s LexicalEnvironment to oldEnv.
    7. Return blockValue.

    NOTE: No matter how control leaves the Block the LexicalEnvironment is always restored to its former state.

    So what happens here?

    When the block is evaluated, a new lexical environment is created, with the current lexical environment as "parent". The new environment replaces the current environment for the duration of evaluating the block.

    If I use a block-scoped declaration, how is the surrounding LexicalEnvironment affected?

    Other than it is temporarily replaced, it is not affected at all.

提交回复
热议问题