"You do not know JavaScript (on)," notes - dynamic scope

Let scope as a dynamic scope at runtime to dynamically determine the form, rather than statically determined form when writing code. Dynamic scope and function scope is not concerned with how and where the statement declared, only care about where they call from. In other words, the scope chain is based on the call stack, rather than the code nested scopes.

Lexical scoping:

function foo() {
    console.log( a ); // 2
}
function bar() {
    var a = 3;
    foo();
}
var a = 2;
bar();

Lexical scoping let foo () is a reference to the global scope by RHS a, thus the output 2.

Dynamic scope:

function foo() {
    console.log( a ); // 3(不是 2 ! )
}
function bar() {
    var a = 3;
    foo();
}
var a = 2;
bar();

In fact JavaScript does not have dynamic scope, it only lexical scoping so that the case is only lexical scoping actual situation

The main difference: lexical scope is determined when writing the code or definition and dynamic scope is determined at runtime. (This also!) Lexical scope function declarations attention where attention and dynamic scope where the function is called from.

Guess you like

Origin www.cnblogs.com/simpul/p/11027205.html