Skip to content

JavaScript Advanced (II)—Lexical Scope

About 192 wordsLess than 1 minute

javascript

2020-02-10

Scope

Scope refers to the area in the program source code that defines variables.

Scope specifies how to find variables, that is, determine the access rights of the current code to the variables.

Lexical scope

In JavaScript, the lexical scope is used, that is, the static scope.

The lexical scope stipulates that the scope of a function is determined when the ** function is defined.

Example

var a = 1
function foo() {
  console.log(a)
}
function bar() {
  var a = 2
  foo()
}
bar()

The execution result of this example is 1.

In this example, since the scope of the function foo is determined when it is defined, even in the function bar, there is a definition of the same variable name a. However, since the scopes of the two functions are independent of each other when they are defined, the function foo looks for the local variable a in its scope, and it is not found. Continue to search for the previous layer of code from its writing position, so the output result is 1.