This is the 6th day of my participation in the August More Text Challenge
Lexical scope and dynamic scope
- Lexical scope: the scope of a function is
The function definitions
It’s time to decide - Dynamic scope: the scope of a function is
A function call
I decided to do that
Here’s an example:
let a = 2;
function foo() {
console.log(a); // Will output 2 or 3?
}
function bar() {
let a = 3;
foo();
}
bar()
Copy the code
Assuming that JavaScript uses lexical scoping (also known as static scoping), let’s examine the execution:
Function foo looks inside foo to see if there is a local variable a. If there is no local variable A, it looks at the code level above foo based on where it was written, so a equals 2, so it prints 2.
Assuming JavaScript is dynamically scoped, let’s examine the execution:
If I execute foo, I still look inside foo to see if there’s a local variable a. If not, the a variable is looked up from within the scope of the calling function, that is, the bar function, so the result prints 3.
As we said earlier, JavaScript uses lexical scope, so the result for this example is 2.
The lexical scope is determined statically at code time; Dynamic scopes don’t care how or where functions and scopes are declared, only where they are called from. In other words, the scope chain is based on the call stack, not the scope nesting in the code.
Javascript does not have dynamic scope; it has lexical scope, which is straightforward. However, its eval(), with, and this mechanisms are somewhat like dynamic scopes and should be used with special care.
Lexical scope is determined at code writing or definition time, while dynamic scope is determined at run time (also this!). . Lexical scopes focus on where functions are declared, while dynamic scopes focus on where functions are called from.
- This is like dynamic scope
- JavaScript execution is statically scoped