Detailed examples of JavaScript static and dynamic scopes


Static scope refers to a piece of code whose scope has been determined before it is executed, or simply where it can be applied (variables) before it is executed.

Dynamic Scope – The scope of a function is determined when a function is called.

JavaScript uses lexical scope, that is, static scope.

// Static scope:
var a = 10;
function fn() {
  var b = 1;
  console.log(a + b);
fn(); // 11

When creating the FN function, we have determined which variables it can work on. If there is a variable in the function fn, we can directly manipulate the variable a.

If not, look up to the next level, which is the static scope.

// Dynamic scopes:
function foo() {
function bar() {
  var a = 3;
var a = 2;
bar(); // 2;

Bar calls, foo in bar is called, foo function needs to find variable a, because JavaScript is lexical scope (i.e. static scope), foo is parsed in global scope.

So you can only find a in the global scope, and the output is 2, not a in the bar scope. If the dynamic scope is adopted by js, then foo calls in bar, and queries a in bar first, and the output is 3.

Ps: Here’s a look at the static scope of JavaScript

Scope refers to the area in the code where variables are defined. Scope specifies how to find variables, that is, determine the access rights of the current code to variables.

Static scope and dynamic scope

Static scope means that the scope of a function has been determined at the time of function definition, while dynamic scope means that the scope of a function is determined at the time of operation. Here is a piece of code:

var value = 1;
function foo() {
function bar() {
    var value = 2;

If this code accesses variables in a static scoping manner, then when performing foo () functions, it first checks whether there is a definition of local variable value in the function. If not, it looks up the previous code, VaR value = 1; and finds the definition of value is 1, so output 1.
If this code accesses variables in a dynamic scoping manner, the foo () function is executed by first looking for the existence of a definition of local variable value from within the function, and if not, by looking up the scope of the caller’s bar () function, VaR value = 2;, so output 2.
JavaScript accesses variables in a static scoping manner, so the output of this example is 1.

The common language that uses dynamic scopes is bash.

Recommended Today

Do arm linux cross compilation once

Cross compilation Why cross compile In fact, cross compilation is relative to native build. I believe that when you first learn C / C + + languages, you write programs on the computer, then compile and generate executable files on the computer, and finally run them on the computer. The whole process of editing, compiling […]