当前位置:网站首页>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 :
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 
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
letcommand , The variables it declares are “ binding ”(binding) This area , No longer affected by the outside .In code block , Use
letBefore 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
- ES5 Only global scope and function scope , There is no block-level scope . This will lead to Code 1 Medium
var aWill be lifted to the top . - 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
- ES5 Only Global scope and function scope , There is no block-level scope .
- 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 .
ES5 Regulations , Functions can only be declared in the top-level scope and function scope , Cannot declare... At block level scope .
however !! Browsers don't follow this rule It also supports declaring functions in block level scopes .
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 .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
letHandle .
Look a little bit around , I read it several times , Write about your understanding .
ES5 Block level scope declaration function is not allowed in , But it is supported in browsers .
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 .
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
In browser , The top object is window, but Node and Web Worker No, window.
The browser and Web Worker Inside ,self It also points to the top object , however Node No, self.
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 :
varCommand andfunctioncommand .ES6 In addition to adding
letandconstcommand , There are also two ways to declare variables :importCommand andclasscommand .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
边栏推荐
- 南京商品房买卖启用电子合同,君子签助力房屋交易在线网签备案
- Tips for using jeditabletable
- redis故障处理 “Can‘t save in background: fork: Cannot allocate memory“
- 登山小分队(dfs)
- Tronapi-波场接口-源码无加密-可二开--附接口文档-基于ThinkPHP5封装-作者详细指导-2022年7月6日-新手快速上手-可无缝升级tp6版本
- One click deployment of highly available emqx clusters in rainbow
- Basic data types and string types are converted to each other
- 测试踩坑 - 当已有接口(或数据库表中)新增字段时,都需要注意哪些测试点?
- Interpolation lookup (two methods)
- Rainbow combines neuvector to practice container safety management
猜你喜欢

为什么要选择云原生数据库

JS的操作

Calling the creation engine interface of Huawei game multimedia service returns error code 1002, error message: the params is error

Rapid integration of authentication services - harmonyos platform

Ebpf cilium practice (2) - underlying network observability

Obsidan之数学公式的输入

How to integrate app linking services in harmonyos applications

一种适用于应用频繁测试下快速查看Pod的日志的方法(grep awk xargs kuberctl)

Are you holding back on the publicity of the salary system for it posts such as testing, development, operation and maintenance?

Improve the delivery efficiency of enterprise products (1) -- one click installation and upgrade of enterprise applications
随机推荐
Improve the delivery efficiency of enterprise products (1) -- one click installation and upgrade of enterprise applications
Through the "last mile" of legal services for the masses, fangzheng Puhua labor and personnel law self-service consulting service platform has been frequently "praised"
【MySQL】数据库进阶之触发器内容详解
Count sort (diagram)
let const
Rainbow combines neuvector to practice container safety management
Teach you how to select PCB board by hand (II)
Golang 编译约束/条件编译 ( // +build <tags> )
打通法律服务群众“最后一公里”,方正璞华劳动人事法律自助咨询服务平台频获“点赞”
Merge sort and non comparison sort
Ebpf cilium practice (2) - underlying network observability
Are you holding back on the publicity of the salary system for it posts such as testing, development, operation and maintenance?
What are the advantages of commas in conditional statements- What is the advantage of commas in a conditional statement?
更改当前文件夹及文件夹下文件日期shell脚本
Practice of combining rook CEPH and rainbow, a cloud native storage solution
POJ - 3784 running medium
Componentspace2022, assertions, protocols, bindings, and configuration files
Rsync remote synchronization
Grpc, oauth2, OpenSSL, two-way authentication, one-way authentication and other column directories
GFS distributed file system