JavaScript Basics – Scopes

Source: Internet
Author: User

JavaScript Basics – Scope What is scope

A scope defines a series of rules for where a variable is found and how it is found . Usually we define a variable in JS with a certain range of calls, such as global variables can be called anywhere, and this range is usually what we mean, the scope of the JS is different from C + +, then what is different, please first with me to understand JS simple compiler principle

Compilation principle

JS is a scripting language, but in fact it also needs to be compiled (PS. generally scripting languages only need to be "interpreted", not "compiled"). However, unlike other traditional compilation languages (such as Java), JS does not compile the code ahead of time and waits for execution, but is quickly compiled and then executed quickly (usually within a few microseconds). Even if there is such a difference, in fact they are roughly the same as the editing process, mainly divided into three stages:
1. Word segmentation/Lexical analysis
A participle is a splitting of an expression, for example var a = 5; , the compilation engine decomposes it into var ,,, a = 5 and ; . Lexical analysis and Word segmentation, its role is to analyze the expression of the meaning of each component, similar to a sentence in what is the subject, predicate and so on.
2. parsing the Code
The second step is to parse the code. In this process, an abstract syntax tree (ast,abstract Syntax tree) is generated that is nested in the first step decomposition of each "small element". As an example of the above expression, when the var a = 5; root node is var , it has two child nodes, one is, one is, and the a following is = = a child node 5 .

3. code Generation
This process generates code that can be executed and is machine-oriented. In this process, the machine starts assigning memory to variables, building scopes, and so on.

Understanding Scopes

JS code in the compilation and execution of the entire process, there are three "characters" play an important role, respectively, the engine, compiler and scope. How do you understand these three "characters"? The engine is the eldest of the three, responsible for compiling and executing the JS code, the compiler is responsible for parsing the code, code generation, etc., and the scope is responsible for managing the scope of each variable in the code that should be active. Three people do their own work, to ensure the smooth operation of JS on the platform.

Work flow

The engine, the compiler and the actors each assume their own responsibility, then how do the three coordinate the work? var a = 5;as an example.
1. In the first compilation phase, the compiler asks the scope if there are any variables a , and if so, the compiler ignores the statement, and if not, generates a variable in the scope a ;
2. During the code generation process, the compiler assigns the 5 variable a ;
3. Finally, the engine in the execution of the code process, will also ask the scope where there is no a , have to take its value to use, if not, go to other places to find (specifically where, continue to look down).

How to find

The engine in the process of executing code, for example var a = 5; , many books and blogs will move out two concepts: Left find (LHS) and right to find (RHS), and then explain a lot of, in fact, left to find is to find the variable, right-looking is to find the value of the variable, if this understanding, It's easy to know when to use the left lookup and when to use the right look.
Later, I researched it myself, and found that the only function of the left and right lookups was to identify the engine to find the return error, and if the variable was not found, the ReferenceError value (attribute) of the variable could not be found TypeError . If there are other functions, please add.

Nested scopes

Nesting scopes are better understood, but here are two points to note: One recognizes that JS is a function scope, scoped to a function, and the second distinguishes between nested scopes and closures.

function foo (a) {Console.log (A + b);} var B = 2;foo (2); 4

The above code is a simple nested scope example, globally defined b , defined in the function a , is nested in the global scope of the function foo can be called b , but the global scope cannot be called a .
When the engine looks for a variable, it is first searched from the scope of the code being executed, and if it is not found, it is then looked up in the scope of the outer level.

Further understanding of scopes

In the compile phase, the scope is formed, and when the engine executes the code, the scope rules begin to define how the engine will take the variable or value. Let's give an example.

In the above example, nested three-layer scope, the first layer is the global scope, the second layer is the scope of foo the function, the third layer is bar the scope of the function. When the engine executes a piece of code, the rule looks like this:

    • First in the current scope of the search, to find the direct call, can not find just want to go on a layer of scope to continue to find, and then can not be found to go up, until the global scope;
    • If you define a variable at the current scope that is the same as the outer scope, whichever is the current scope.

In the first rule, when you define a variable, you need to precede it with the variable, and var if not, in a non-strict mode, the variable is created in the global scope, and an error is made in strict mode.
In the second rule, if you still want to call the global that duplicate variable in the current scope, you can define it window.a = 5; , and go directly when window.a you call it.

Note: Calling with and eval() changing the execution environment scope is not recommended, because they will bring performance problems, here is not explained in detail, you can refer to the article later reference.

Extension: block level scope in JS

The function scope of JS brings flexibility, but in some places there is inconvenient, for example, in the for if statement, we may only need to {} define some temporary variables in them, do not want to pollute the current scope. Based on these issues, the ES6 has let added const two keywords to implement block-level scope definition variables.
letThe use of the var same, but the scope is different. For example:

    For (Let I =0; i<3; i++) {        console.log (i);    }//0,1,2    cosole.log (i);//i is undefined

constis also used to define a variable, but it defines a static variable (constant), and once defined, the re-assignment will give an error.

   var foo = true;    if (foo) {        var a = 2;        Const B = 3; Defines        a constant a = 3;         b = 4; error!    }    Console.log (a); 3    Console.log (b);//referenceerror!
 
Reference documents
    • You-dont-know-js
    • JavaScript authoritative Guide
    • JavaScript Advanced Programming

JavaScript Basics – Scopes

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.