Easy to understand lexical scope

Time:2022-5-21

What is lexical scope

In short, it is the function scope determined at compile time

example

var value = 1;

function bar() {
    var value = 2;
    function foo() {
        console.log(value);
    }
    foo();
}

bar(); //2

The answer to the above code is 2. Because bar and foo are nested, their lexical scope is already nested in the compilation stage

var value = 1;
function foo() {
    console.log(value);
}
function bar() {
    var value = 2;
    foo();
}
bar(); // 1

The above code is 1. Because Foo and bar are of the same level, it is determined that the lexical scope of the two is equal, not nested.