How to Understand the scope in JavaScript

Source: Internet
Author: User

How to Understand the scope in JavaScript

What are variables and scopes?

Variable: Simply put, it is to save a name for a specific value within a specific period of time. Because there is no rule to define a variable that must save a certain data type value, therefore, the value of a variable and its data type can be changed at will within the script lifecycle. The variable may contain two different data types: basic type value and reference type value. Basic data types include Undedind, Null, Boolean, Number, String, and Symbol (New in es6). Boolean, Number, String, and Symbol are also called Basic packaging types. Reference Type: In simple terms, all the other basic types are the reference type. It may not be rigorous. Let's take a look.

Scope: we already know that the function of a variable is to store values. How can we access or modify values? In other words, where do these variables live? More importantly, how do we find them? As Shakespeare said: To be, or not to be: that is the question! Therefore, we need a set of well-designed rules to store variables, and we can easily find these variables. This set of rules is called scope!

Compilation principles

Before learning how to act on a rule, we must first understand the compilation principle, that is, how the code works after being written. In a strongly typed language, to execute a piece of source code in a program, you must first compile it. The compilation process involves three steps:

1. Word Segmentation/lexical analysis. This process splits character strings into meaningful code blocks, which are called lexical units, such as var a = 2. This code is usually divided into the following lexical units: var, a, =, 2 ,;. Whether a space is treated as a lexical unit depends on whether the space is meaningful to the language.

2. parsing/syntax analysis. This process is to convert the array of lexical units into a Tree consisting of step-by-step element nesting representing the Syntax structure of the program, called the Abstract Syntax Tree (AST ). To put it simply, for the source code in a programming language, the code in the source code is mapped to every node in the tree by constructing a syntax tree.

3. Code Generation. The process of converting AST (Abstract syntax tree) to executable code is called code generation. To put it simply, convert the AST of var a = 2; into a command that the machine can recognize, create a variable a, and store its value 2 in.

The JavaScript engine is much more complex than the three-step compiler in the compilation process, and there are specific steps in the syntax analysis and code generation phases to optimize the performance, I do not know the specific steps, including optimizing redundant elements, because the compilation principle is excerpted from the original words in the book "you don't know JavaScirpt, hahaha, isn't it delicious !!! Most JS compilation occurs before code execution, and the compilation is completed immediately.

Understanding Scope

See var a = 2. Normal people think this is a sentence, because the statement does not contain ',' or '. 'Statement separator, but in the JS engine, there are two declarations: Variable Life and value assignment. The first step is the lexical analysis process. The var a = 2 is broken down into lexical units, then the syntax analysis generates an abstract syntax tree, and finally the code is executed. Specifically, var a = 2; is divided into var a and a = 2. When the compiler encounters var, the compiler will ask whether a variable with this name already exists in the same scope. If so, the new let and const in es6 will be ignored ), if no variable exists, a new variable is generated in the current scope and named. Next, the compiler generates the Code required during runtime for the engine. This code is used to handle the assignment of a = 2. When the engine is running, it first finds whether there is a variable named a in the current scope. If there is a variable, it assigns a value. If not, it continues to search for the upper-level scope. If it is not found, if the top-level global scope of the scope cannot be found, an error is thrown. Therefore, the variable assignment operation always performs two steps. If the variable is not declared, a variable is generated in the current scope (in strict mode, an error is returned if the variable is assigned an undeclared value ), then, the runtime engine searches for the change volume in the scope. If the change volume is found, the value is assigned.

Scope nesting

How is the scope formed? In short, it is determined by the execution environment. Each execution environment has a variable object associated with it, and all variables and functions in the environment are saved in this object, in the global environment, the execution is called global scope in the global variable object, and the variable objects stored in the function constitute a local scope. When the code is executed in an environment, a scope chain of the variable object is created, and the front end of the scope chain is always the variable object in the environment where the current code is located. The compiler searches for variables at the level of the scope chain until the global execution environment, that is, the global scope. When one scope is nested in another scope, the scope is nested. Therefore, if a variable cannot be found in the current scope, the engine searches for the variable in the outer nested scope along the scope chain, until the variable is found or at the top of the scope chain (global scope. As follows:

function foo(a){    console.log(a+b);}var b = 2;foo(2); // 4

In this Code, the engine will first ask foo's scope in the foo function. Have you ever seen B? Foo scope: never seen before. Roll the cursor. Then the engine climbed up along the scope chain to the global scope, and then asked: Have you ever seen B in the global scope? Global scope: Well, I have seen it. Give it to you.

Nested scope rules are very simple, that is, starting from the current scope and looking up at the first level. The search process stops until the outermost global scope is reached!

As mentioned before, variables are always searched before being assigned values. If the variable to be assigned is not found in non-strict mode, A variable with this name is implicitly created in the global scope and returned to the engine. As follows:

function foo(a){    console.log(a+b);    b = a;}foo(2); // 4

OK.

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.