scope closure

scope

One of the most fundamental features of almost any programming language is the ability to store a value in a variable and then access or modify that value later. In fact, it is this ability to store and access the values ​​of variables that brings state to the program.

Where are these variables? How do programs find them when they need them?

These problems illustrate the need for a well-designed set of rules for storing variables and finding them easily later, a set of rules called scoping.

For var a = 2processing:

The assignment of a variable will perform two actions, first the compiler will declare a variable in the current scope (if it has not been declared before), then at runtime the engine will look for the variable in the scope, and if it can find it, it will It assigns.

How the engine performs lookups when looking for variables affects the final lookup results.

The LHS query is performed when the variable appears on the left side of the assignment operation, and the RHS query is performed when it appears on the right side.

console.log(a)A reference to a is an RHS reference, where a is not assigned any value. Accordingly, the value of a needs to be looked up and obtained so that the value can be passed to console.log(..).

a = 2The reference to a is an LHS reference because we don't actually care what the current value is, just find a target for the assignment operation =2.

Scope is a set of rules for finding variables by name.

Nesting of scopes occurs when a block or function is nested within another block or function. When a variable cannot be found in the current scope, the engine will continue to search in the outer nested scope until the variable is found, or the outermost scope is reached.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326272064&siteId=291194637