当前位置:网站首页>let const

let const

2022-07-07 08:41:00 lazytomato

start

  • I come to study again ES6 了 .
  • Because I found that I was using some ES6 Of API When , I always think it's almost funny .
  • Take some time. , Combined with the form of mind mapping , Go through it systematically .
  • ღ( ´・ᴗ・` ) finger heart

Mind mapping :
 Insert picture description here

1. let and const What are the characteristics of ( The same thing )

1.1 No variable promotion

console.log(lazy) // undefined
var lazy= ' lazy '


console.log(tomato) // tomato is not defined
let tomato= ' How are you? '

Discuss

var a = 1
function s() {
    
  console.log(a)
  let a = 2
  //  If you don't write  `let a = 2`  above console.log(a)  prints  1

  //  But I wrote  `let a = 2` Cannot access 'a' before initialization
}
s()

How to explain the above code

  • Variable promotion is just a grammatical definition .

  • In fact, the essence is that a piece of code is in the context creation stage ( That is, the compilation phase ) Is able to recognize var and let Of the created variable

  • Only the operation of the two is different : Yes var The defined variable is initialized to undefined, and let The defined variable is still uninitialized .

1.2 Repeat the statement and report the error

Code

var a = '1'
console.log(a)
var a = '2'
console.log(a)

let b = '1'
console.log(b)
let b = '2'  // Uncaught SyntaxError:Identifier 'b' has already been declared  Translate : unnamed   Grammar mistakes :  identifier “b” declared 
console.log(b)

reflection

  • Use let To declare a variable with the same name twice , It's a direct error , The whole code is not running .( The running effect can be seen in the following screenshots )
  • Run the upper and lower code separately ,var It supports repeated statements .

Run a screenshot
 Insert picture description here

1.3 Do not bind the global scope

Code

var a = '1'

let b = '2'

console.log(window.a)  // 1
console.log(window.b)  // undefined

explain

The properties of top-level objects are linked to global variables , Is considered to be JavaScript One of the biggest design failures of language . This kind of design brings a few big problems , First of all, we can't report an undeclared variable error at compile time , Only the runtime knows ( Because global variables can be created by the properties of top-level objects , And the creation of attributes is dynamic ); secondly , It's easy for programmers to unknowingly create global variables ( For example, typing mistakes ); Last , The properties of top-level objects can be read and written everywhere , This is very bad for modular programming . On the other hand ,window Objects have entity meanings , Refers to the browser's window object , The top-level object is an object with entity meaning , It's also inappropriate .

ES6 To change that , On the one hand, it stipulates that , To maintain compatibility ,var Command and function Global variables declared by the command , It is still the property of the top-level object ; On the other hand, it stipulates that ,let command 、const command 、class Global variables declared by the command , Properties that do not belong to the top-level object . in other words , from ES6 Start , Global variables will gradually decouple from the properties of the top-level object

- Content comes from ECMAScript 6 Introductory tutorial _ Ruan Yifeng

Personal thinking

For myself , This place is a very vague point . come to know The properties of top-level objects are linked to global variables After the shortcomings of , The reason for this is well understood .

Make a note of : let command 、const command 、class Global variables declared by the command , Properties that do not belong to the top-level object

1.4 Temporary dead zone

Code

var tmp = 123;

if (true) {
    
  tmp = 'abc'; // ReferenceError: Cannot access 'tmp' before initialization  Translate   Misquote :  Cannot access before initialization  'tmp‘ 
  let tmp;
}

reflection

  • As long as there is... In the block level scope let command , The variables it declares are “ binding ”(binding) This area , No longer affected by the outside .

  • In code block , Use let Before a command declares a variable , This variable is not available . This is in grammar , be called “ Temporary dead zone ”(temporal dead zone, abbreviation TDZ).

1.5 Block level scope

Look at the code first

Code 1

if (false) {
    
  var a = 1
}

console.log(a) // undefined

console.log(b) // ReferenceError: b is not defined

Code 2

let a = 1
{
    
  let b = 2
}

console.log(a) // 1
console.log(b) // ReferenceError: b is not defined

reflection

  1. ES5 Only global scope and function scope , There is no block-level scope . This will lead to Code 1 Medium var a Will be lifted to the top .
  2. and let const It is declared that there is a block level scope , It cannot be read externally .

Block level scope

MND The official description of : Block scope

Any pair of curly braces {} The statement sets in all belong to a block , All variables defined in this are invisible outside the code block , We call it a block level scope .

summary

  1. ES5 Only Global scope and function scope , There is no block-level scope .
  2. ES6 The block level scope of must have braces , If there are no braces ,JavaScript The engine assumes that there is no block level scope .

What I understand is ,ES6 Pay attention to if and trycatch Brace for , There will be block level scopes .

2. Difference

const The data stored in the memory address pointed to by the declared variable must not be changed .

Recommended const Declare variables , Ensure that the variable memory address remains unchanged , Can reduce the bug Happen .

3. Expand

3.1 Can a function be declared in a block level scope ?

For example, in if , trycatch Function declared in .

  1. ES5 Regulations , Functions can only be declared in the top-level scope and function scope , Cannot declare... At block level scope .

  2. however !! Browsers don't follow this rule It also supports declaring functions in block level scopes .

  3. ES6 Introduced block level scope , Explicitly allow functions to be declared in block level scopes .ES6 Regulations , In block scope , Function declaration statements behave like let, Cannot be referenced outside the block level scope .

  4. If the processing rule of the function declared in the block level scope is changed , Obviously it's going to have a big impact on old code . In order to reduce the incompatibility ,ES6 stay appendix B It says , Browser implementation can not follow the above rules , Have their own Behavior mode .

    • Allow functions to be declared within a block level scope .
    • Function declaration is similar to var, That is, it will be promoted to the head of the global scope or function scope .
    • meanwhile , Function declarations are also promoted to the head of the block level scope in which they reside .

    Be careful , The above three rules are only for ES6 The browser implementation of , The implementation of other environments does not have to comply with , Still treat the function declaration of the block level scope as let Handle .

Look a little bit around , I read it several times , Write about your understanding .

  1. ES5 Block level scope declaration function is not allowed in , But it is supported in browsers .

  2. ES6 Block level scopes explicitly allowed in can declare functions , But in the block level scope , Function declaration statements are similar let. External cannot be quoted .

  3. In order to reduce the ES6 The change of ES5 Influence , Implementation of browser , You can not follow ES6 Specified realization , Realize as follows :

    • Allow functions to be declared within a block level scope .

    • Function declaration is similar to var, That is, it will be promoted to the head of the global scope or function scope .

    • meanwhile , Function declarations are also promoted to the head of the block level scope in which they reside .

      # The above three are only for ES6 Browser To be effective .

3.2 Top objects

  1. In browser , The top object is window, but Node and Web Worker No, window.

  2. The browser and Web Worker Inside ,self It also points to the top object , however Node No, self.

  3. Node Inside , The top object is global, But no other environment supports .

3.3 ES6 Six ways to declare variables

  • ES5 There are only two ways to declare variables :var Command and function command .

  • ES6 In addition to adding let and const command , There are also two ways to declare variables :import Command and class command .

    therefore ,ES6 Altogether 6 Ways to declare variables .

end

  • In fact, this is the third time I have learned this let and const 了 , Maybe not the last time .

  • Of course, this time is also very rewarding , for example :

    • Block level scope ;

    • Declaration of function in block level scope ;

    • let const Will the variable increase ;

  • secondly let const New features , They are all used to solve previous pain points and problems , Knowing the reason and looking at the result is very clear .

  • Written in 2022/07/06-23/10

原网站

版权声明
本文为[lazytomato]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207070556050697.html