当前位置:网站首页>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
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
- 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 . - 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
let
Handle .
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 :
var
Command andfunction
command .ES6 In addition to adding
let
andconst
command , There are also two ways to declare variables :import
Command andclass
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
边栏推荐
- 数据中台落地实施之法
- National standard gb28181 protocol video platform easygbs adds streaming timeout configuration
- Leetcode 1984. Minimum difference in student scores
- leetcode135. Distribute candy
- iptables 之 state模块(ftp服务练习)
- FPGA knowledge accumulation [6]
- One click installation of highly available Nacos clusters in rainbow
- Improve the delivery efficiency of enterprise products (1) -- one click installation and upgrade of enterprise applications
- [Chongqing Guangdong education] audio visual language reference materials of Xinyang Normal University
- Several ways of lambda used in functions in kotlin (higher-order functions)
猜你喜欢
About using CDN based on Kangle and EP panel
Quick sorting (detailed illustration of single way, double way, three way)
In go language, function is a type
idea里使用module项目的一个bug
【踩坑】nacos注册一直连接localhost:8848,no available server
Data type - integer (C language)
Practice of combining rook CEPH and rainbow, a cloud native storage solution
iptables 之 state模块(ftp服务练习)
2-3 lookup tree
What is the method of manual wiring in PCB design in 22protel DXP_ Chengdu electromechanical Development Undertaking
随机推荐
leetcode134. gas station
[untitled]
ES6_ Arrow function
注解@ConfigurationProperties的三种使用场景
Data type - integer (C language)
调用华为游戏多媒体服务的创建引擎接口返回错误码1002,错误信息:the params is error
【踩坑】nacos注册一直连接localhost:8848,no available server
Fluentd is easy to use. Combined with the rainbow plug-in market, log collection is faster
说一个软件创业项目,有谁愿意投资的吗?
[Yugong series] February 2022 U3D full stack class 008 - build a galaxy scene
Are you holding back on the publicity of the salary system for it posts such as testing, development, operation and maintenance?
Implement your own dataset using bisenet
Data type - floating point (C language)
如何在HarmonyOS应用中集成App Linking服务
Arm GIC (IV) GIC V3 register class analysis notes.
IP guard helps energy enterprises improve terminal anti disclosure measures to protect the security of confidential information
Splunk query CSV lookup table data dynamic query
Train your dataset with swinunet
Implementation method of data platform landing
Required String parameter ‘XXX‘ is not present