JS詞法環境變化

LexicalEnvironment and VariableEnvironment are what keep track of variables during runtime and correspond to block scope and function/module/global scope respectively. Here's an example based on my reading of the spec http://www.ecma-international...oop

0: function do_something() {
1: var a = 1;
2: let b = 2;
3: while (true) {
4: var c = 3;
5: let d = 4;
6: console.log(b);
7: break;
8: }
9: }
10:
11: do_something();
When we first call do_something() it creates an ExecutionContext.this

ExecutionContext:rest

LexicalEnvironment:
    b -> nothing
    outer: VariableEnvironment //here should VariableEnvironment
VariableEnvironment:
    a -> undefined, c -> undefined
    outer: global
...

Entering the while loop creates a new lexical environment:code

ExecutionContext:get

LexicalEnvironment:
    d -> nothing
    outer:
        LexicalEnvironment
            b -> 2
            outer: global
VariableEnvironment:
    a -> 1, c -> undefined
    outer: global
...

Now when we look up variables, we can always fall back on whatever is contained in outer. This is why you can access global variables from within functions. It is also why we can access console.log(b) from within the while block even though it lives in the outer scope.it

When we leave the while block we restore the original lexical environment.io

ExecutionContext:console

LexicalEnvironment
    b -> 2
    outer: global
VariableEnvironment:
    a -> 1, c -> 3
    outer: global

Therefore d is no longer accessible.function

Then when we leave the function we destroy the execution context.module

I think that's the gist of it.

Although this explanation is based on ECMA-262 6.0 because of let, the LexicalEnvironment is defined similarly in 5.1 where it's used to temporarily bind variables in with, and in the catch clause of a try/catch.

相關文章
相關標籤/搜索