How big is GitHub? How big is GitHub

Static scope

JavaScript uses lexical scope, which is static scope.

Some say dynamic scopes are used

Example:


      var value = 1;
      function foo() {
        console.log(value);
      }
      function bar() {
        var value = 2;
        foo();
      }
      bar();//1 Because JS uses static scope

Copy the code

Remember that the scope of JavaScript is defined at the time it is defined.

So in this case, we’re going to look for value, first in foo, nothing, and then literally chain up from its scope, outside of foo(), value = 1.

Take a look at the scope chain

There are three scopes in this example. Global scope and the following two horizontal ones: Foo and bar. So when we can’t find a value in foo, we have to look globally, not in bar.

About the closure

Bar () should not be a closure in this example. Why?

Because foo in it does not reference any variables in the scope of bar, it does not save anything and is therefore garbage collected.

To consider

var scope = "global scope";
function checkscope(){
    var scope = "local scope";
    function f(){
        return scope;
    }
    return f();
}
checkscope();
Copy the code

This is a closure, just try to analyze it.