Home >Web Front-end >JS Tutorial >Lexical vs. Dynamic Scoping: What's the Difference and Why Do We Prefer Static Scoping?
Understanding lexical scoping can be simplified through examples.
Lexical Scoping (Static Scope)
In lexical scoping, every inner level can access its outer levels. An example in C-like syntax:
void fun() { int x = 5; void fun2() { printf("%d", x); } }
Dynamic Scoping
Dynamic scoping allows inner levels to access variables from dynamically determined outer scopes, depending on the call chain. A C-like syntax example:
void fun() { printf("%d", x); } void dummy1() { int x = 5; fun(); } void dummy2() { int x = 10; fun(); }
Here, fun can access x from either dummy1 or dummy2, or any other function that calls fun with x declared within it.
dummy1(); // Prints 5 dummy2(); // Prints 10
Key Differences
Static scoping can be determined at compile-time, while dynamic scoping depends on the runtime call chain. Dynamic scoping is like passing references of all variables to the called function.
Static scoping is often preferred because it simplifies comprehension. Most languages, including Lisp, eventually adopted this approach. Dynamic scoping can introduce complexity when the call chain is dependent on runtime conditions.
The above is the detailed content of Lexical vs. Dynamic Scoping: What's the Difference and Why Do We Prefer Static Scoping?. For more information, please follow other related articles on the PHP Chinese website!