Related knowledge of JS scope

Source: Internet
Author: User

As we all know, before ES6, JavaScript is not block-scoped , as shown in:

Students who have studied other languages must be a little surprised. Because JS is still different from other languages, in ES5, only the global scope and function scope, and there is no block scope, of course, we can implement the block scope function. Look at the following code:

In this piece of code, we use the immediate execution function (Iife) to create a local function that mimics the block-level scope. In the ES5 era, the scope of JavaScript only uses global scope and local scope. In the ES6 era, the block-level scope of the debut.

first, about the ES5 era  1. Variable Promotion    

When it comes to JS's variable promotion, we have to say a bit about the lexical analysis of JS. It is known that the JS code is executed from top to bottom, but before the JS code is executed, the lexical analysis is performed first. So JS run to be divided into lexical analysis and program execution of two stages.

JS Lexical analysis is divided into 3 main steps:

1. Parse parameter: If the function is a physical parameter, add the parameter property to the currently active object, which defaults to undefined.

2. Analysis Variable declaration: If there is a declaration such as Var A, if there is no attribute then increase the property, if already exist do not do the operation. The default is undefined. The assignment of a variable is performed at the execution stage, that is, when the variable is executed, a = 11.

3. Analysis function declaration: like function A () {}, if the current active object does not have this property is added otherwise override the property as method A.

, in this code, according to the general logic, the first console.log will be an error "A is not defined".

But in fact, according to the second step of JS lexical analysis, the Var a declaration is advanced to the top of the code. But a=1 this assignment does not, so the correct steps for this function are:

This is known as variable elevation.

2. Function Promotion    

In JS, our common functions are created in three ways-function constructors (deprecated, not analyzed here), function declarations and function expressions. The code for the first line below is a function declaration, and the second is a function expression.

      

1 function fn1 () {} 2 var fn2=function() {};

In both of these ways, the usual way of function expressions is the same as the normal variable var a=1, so it is also affected by the variable promotion. In the other case, the function declaration has the function promotion, and the function promotion is higher than the variable promotion priority! Therefore the above fn1 and FN2 are printed before creating the following results:

Based on the analysis of variable elevation and function promotion:

Therefore, FN1 is promoted to the front as a function declaration, and FN2 is first created as a variable and referred to the top and then assigned in the corresponding position.

3. Scope Chain    

We're talking about JS. In the ES5 era there is no block scope, only local scope and global scope. A scope chain is used to ensure orderly access to all variables and functions that the execution environment has access to. Look, according to the general idea, the B output is 3. The knowledge of the scope chain is used here.

When the function is in the process of execution, first find the variable from within itself. If it is not found, look for it from the scope where the current function is created , and then go up. So we analyze the adjustment function to get. In this function, the value of FN is assigned to FN1 (), which is the return value of Fn1 fn2. When you run FN, the fn2 is run. At this point the interior of FN2 is useless B, so we are going to fn2 to find b=2 in the creation environment . So the output here is 2.

Ii. the era of ES6  1.let and the advent of the const    

First let and foremost const的作用和var是相同的,但是 There is no elevation , and the declaration is a block-level identifier . A block-level scope is formed inside the curly brace, where a let declaration is outside the block-level scope of the access call

1 {2let   a=1;      3 }4 console.log (a)// error

and let and const are prohibited from repeating the declaration :

1 var a = +; 2 var message = 2; 3 // These two will throw a syntax error 4 Let a =5
constants for each const declaration must be initialized , const defined constants cannot be modified, but objects declared with const can modify values , i.e.
  1  const A; //  syntax error: constant uninitialized   2  const b = {  3  Name: ' A '  4  };    5  b.name = ' B '; //   6   7  //   syntaxerror: "Person" is read-only   8  b = {  9  name: ' 
      let and const declarations will not be var promoted to the top of the scope, and if these variables are accessed before the declaration, a so-called temporary Dead Zone (temporal Dead zone) is formed, even if it is relatively safe typeof Operator will also trigger a reference error. For let Example (const is the same):
1 console.log (typeof  value); 2 Let value = 1;
In the above code, let no variable promotion function, that is, the code before let value=1 the temporary Dead Zone (temporal Dead zone), that is, the error value is not defined instead of undefined.
1 console.log (typeof  a); 2 if (1) {3let   a=1; 4 }

In the above code, let is in the block-level scope, so there is no so-called dead-zone in the global scope, so undefined is printed here.

2. Global block scope bindings    in the global scope, the variable declared by Var becomes a property of the Global Object (window in the browser environment). This means that Var is likely to inadvertently overwrite a global variable that already exists.
1 var Test=1; 2 // true
If you use let or const in the global scope, a new binding is created under the global scope, but the binding is not added as a property of the global object. In other words, a let const global variable cannot be overwritten, but only obscured.
1 Const FOO = 1; 2 Window.foo = 2; 3 // 1 4 // 2

In actual development, the let direct substitution with which we are actually using is var的用法是一样的 logical. For variables that require some protection, we want to use the const. By default, const is used only if you really need to change the value of the variable let .

Related knowledge of JS scope

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.