The front end of knowledge: JavaScript basis - Scope and Closures - lexical scope and dynamic scope

Lexical scoping and dynamic scoping

1, the scope:

Scope is defined in the program code refers to a region of variable

JavaScript uses lexical scoping, which is static scope

2, lexical scoping and dynamic scoping

Since JavaScript uses lexical scoping, scope of a function when the function is defined on the decision.

With the corresponding lexical scoping is dynamic scoping, scope of a function when the function is invoked before deciding. 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.

 

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

 

JavaScript is assumed that static scoping, analysis of the implementation process:

Execution foo () function, first look inside foo function value if there is a local variable, and if not, to find the position code on the writing layer, i.e. equal to value 1, so that a printed result.

JavaScript is assumed that dynamic scoping, analysis of the implementation process:

Execution foo () function is still to find from inside the foo function if there is a local variable value, if not, from the scope of the calling function is () function inside the bar to find value variables, so the results will print 2.

As already said, JavaScript uses lexical scoping, so this is an example of the results

Reference article: https: //www.cnblogs.com/xiaohuochai/p/5700095.html

 

Guess you like

Origin www.cnblogs.com/memphis-f/p/12059907.html