You do not know the JS Series [1] - What is the scope

  Almost all programming languages are able to store a variable, and this variable can then be accessed or modified in value, it is the ability to store and access variables of the state to bring the program, then these variables is stored where? How is the program needs time and find them? These problems illustrate the need for a well-designed rules to store variables, and then you can easily find these variables, this set of rules is called a scope .

1, understand compiler theory

  Although JS classified as "dynamic" or "interpreted" scripting language, but in fact it is a compiled language. But unlike traditional compiled languages ​​different is that it is not compiled in advance, compile the results can not be transplanted in a distributed system. Step JS engine compiled with the traditional language very similar to the program for some source code before execution will go through three steps, collectively referred to as "compile."

  • Word / lexical analysis

This process will string composed of characters decomposed into meaningful code blocks, the code block is called lexical unit. For example, consider a program var a = 2;. This procedure will usually be broken down into the following lexical units: var、a、=、2 、;.

  • Parsing / syntax analysis

This process is to convert the flow lexical unit (array) into a nested cascade elements composed of the tree represents the syntactic structure of the program. This tree is known as "abstract syntax tree" (Abstract Syntax Tree, AST) . var a = 2;Child nodes of the abstract syntax tree might be called a top-level node VariableDeclaration, followed by a called Identifier (its value is a), and a child node is called AssignmentExpression. AssignmentExpression a node called NumericLiteral (its value is two) child nodes.

  • Code Generation

AST is converted to executable code is referred to as code generation process is known, is simply have some ways to var a = 2;the AST is converted to a set of machine instructions to create a called a variable (including memory allocation, etc.), and a value stored in a medium.

Compilation flow as shown below:

JS engine complex than traditional compiler-compiler lot, there are specific steps in parsing and code generation phase to optimize the performance, compile occur in the first few microseconds before the code in most cases, the scope of the discussion in the back, js engine in a variety of ways to ensure the best performance.

Tips : We usually write when JS code, the end of a sentence to add a semicolon (;), to facilitate JS compiler.

2, understand the scope of

  We first understand the process of compiling a few terms JS, JS engine, compiler, scope.

2.1 Introduction nouns

  • JS engine : JS responsible for the entire procedure from start to finish compilation process.
  • Compiler : responsible for parsing and code generation.
  • JS engine : responsible for collecting and maintaining a series of queries by the identifier (variable) consisting of all declared and implemented a set of very strict rules that determine the code currently executing access to these identifiers.

2.2. Variable assignment

For var a=2;this code, we think this is a declare a variable and the initial value of 2, in fact, JS engines think there are two completely different states that a process by the compiler at compile time, by another engine runtime processing.

A two-step process:

1. encountered var a, the compiler will ask if there is a scope that name already exists in the collection of variables in the same scope. If so, the compiler ignores the statement and continue to be compiled; otherwise it will be asked to declare a new variable scope in the current scope of the collection, and named a.

2. Next, the compiler will generate the desired engine runtime code which is used to handle a = 2the assignment. It will first ask scoping engine is running, if there is a known as a variable in the current scope of the collection. If so, the engine will use this variable; if not, the engine will continue to look for the variable.

If the engine eventually find a variable, it will be 2 assigned to it. Otherwise it throws an exception.

Tips: statement in advance (hoist) -JS engine when you create a variable, the variable will be raised to the top of the current scope.

Summary: The assignment of variables performs two actions, first compiler will declare a variable in the current scope (if not declared before too), then the engine will look for the variables in scope at run time, if we can find it it will assign.

2.3.LHS query & RHS inquiry

The compiler during compilation of code to generate a second step, the engine is executed, it will be to determine whether it has been declared by finding the variable a. When inquiries were RHS LHS variable appears conducted inquiries at the left side of an assignment operation, when the variable appears on the right.

console.log(a); //对a的引用时RHS引用,这里没有对a赋予任何值,需要查找a的值。

a=2; //对a的引用是LHS引用,因为这里不关心a的值等于多少,只想为 =2 这个赋值操作找到一个目标(变量a);

LHS and RHS means "left or right side of the assignment" does not necessarily mean that "assignment = left or right side of the operator." There are several other forms of assignment, so the concept is best understood as to "who is the target of an assignment (LHS)" and "to find the value of the variable XX, who is the source of an assignment (RHS)".

3, nested scopes

  Scoped variables by name is to find a set of rules. Practice, often it requires taking into account several scopes. When a function block or nested within another block or function, a nested scopes occurs. Therefore, when the current scope of a variable can not be found, the engine will continue to find in the outer nested scopes, until you find the variable, or reach the outermost scope (that is, the global scope) so far.

Reference the following code:

var name='peer';
function sayHello(){
  alert('hello '+ name)
}
sayHello();
// 对name的RHS引用无法在函数sayHello完成,但是可以在上一级作用域中完成。

Scope likened to a building as shown below:

LHS and RHS references will look in the current floor, if not found, it will take the elevator down to the floor, if you still do not find it to continue upward, and so on. Once at the top level (global scope), you may find the variables required, could not find, but in any case the search process will stop.

4, summary

  A scope is a set of rules for determining where and how to find variable (identifier). LHS and RHS inquiry will begin in the current execution scope, if there is a need will continue the search identifier to the superior scope, so that every time an increase in scope, and finally arrived in the global scope, whether it will be found or not found stop. Unsuccessful RHS ReferenceError reference will cause an exception. Unsuccessful LHS references will automatically lead to implicitly create a (non-strict mode) global variables, the scope of knowledge to master these basic enable us to a deeper understanding of the process of compiling JS engine to write a more high-performance code.


Reference:
"You do not know JavaScript"

Guess you like

Origin www.cnblogs.com/peerless1029/p/11894829.html