当前位置:网站首页>[ES6] let and const commands
[ES6] let and const commands
2022-04-21 22:02:00 【Xiao Shen Yue】
let command
characteristic
- No variable promotion
- {} Local variables in a code block
- Temporary time zone — stay let Using variables before variable declaration will report an error
- Inside the same code block ( Same scope ) Cannot repeat declaration
Basic usage
Used to declare variables , Be similar to var, But the declared variable , Only in let The command is valid in the code block
{
let a = 10
var b = 1
}
console.log(a) // Report errors ,a is not defined
console.log(b) //1
It can be used let To solve the closure problem
//es5
var a = []
for(var i=0;i<10;i++){
a[i] = function(){
console.log(i)
}
}
a[6]() //10
//es6
var a = []
for(let i=0;i<10;i++){
a[i] = function(){
console.log(i)
}
}
a[6]() //6
because i yes let Declarative , Current i Only valid in this cycle .
in addition ,for There's another thing about the cycle , The part that sets the loop variable is a parent scope , Inside the circulatory body is a separate sub scope
for(let i=0;i<3;i++){
let i = 'abc'
console.log(i) //abc
}
No variable promotion
var Variable escalation will occur , That is, variables can be used before declaration , The value is undefined.
let There is no variable escalation , The declared variables must be used after the declaration , Otherwise, the report will be wrong
//var
console.log(foo) //undefined
var foo = 2
//let
console.log(bar) // Report errors , In use let Statement bar Before , It doesn't exist
let bar = 3
Temporary dead zone
As long as it exists within the block level scope let command , The variables it declares are bound to this region , No longer affected by the outside world , When the variable is let Before declaration, it is the dead zone of the variable
var tem = 123
{
temp = 'abc' // Report errors
let temp
}
Duplicate statements are not allowed
let Not allowed in the same scope , Repeatedly declare the same variable
// Report errors
function func(){
let a = 10
var a = 1
}
// Report errors
function func2(){
let a = 10
let a = 2
}
Block level scope
Why a block level scope is needed ?
ES5 Only global scope and function scope , There is no block-level scope , This brings a lot of unreasonable scenes
The first scenario : Inner variables may override outer variables
The second scenario : The loop variable used to count is leaked as a global variable
ES6 Block level scope of
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
let It's actually JavaScript Block-level scopes have been added ,ES6 Allow any nesting of block level scopes
function fn(){
let n = 5
if(true){
let n = 10
}
console.log(n) //5
}
The inner scope can define variables of the same name in the outer scope
{
{
let a = 10
{
let a = 20 // It won't make a mistake , Because the two one. a Not in the same scope
}
}
}
Block level scopes and function declarations
ES5 Regulations , Functions can only be declared in the top-level scope and function scope , Cannot declare in block level scope
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
function fn(){
console.log('outside')
}
(function(){
if(false){
function fn(){
console.log('inside')
}
}
fn()
}())
stay ES5 The result is inside, Because in if The function declared inside is promoted to the function header
stay ES6 An error will be reported during the operation
The implementation of the browser can not comply with the above rules , Have your own way of behaving
- 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 , No other environment to follow , Or treat the function declaration of block level scope as let Handle , Function declaration statements inside the block level scope , Not recommended , Use function expressions first
const command
characteristic
- Used to declare a constant
- const Declaration and assignment must be performed simultaneously , In other words, if you only declare that there is no assignment, an error will be reported
- Block level scope
- No variable promotion
- There is a temporary dead zone
- Duplicate statements are not allowed
Declare a read-only constant
const PI = 3.1415
PI = 3 // Report errors , Do not modify const Declare the basic data type
Declaration and assignment must be performed simultaneously
const foo // Report errors
Block level scope
{
const a = 10
}
console.log(a) // Report errors , a is not defined
Variables cannot be promoted , Temporary dead zone , Cannot repeat declaration
{
console.log(a) // Report errors ,const Declared variables can only be used after declaration
const a = 1
const a = 2 // Report errors
}
The essence
const In fact, the address to which the variable is stored cannot be changed .
For basic data types , The value is stored in the memory address pointed to by the variable , Equivalent to constant .
For reference type data , Variables hold pointers to actual data ,const Only ensure that the pointer is fixed , The data structure of variables will not be fixed .
Therefore, you must be very careful when declaring an object as a constant .
const foo = {
}
// It can be for foo Add attribute
foo.name = 'zhangsan'
foo.age = 20
// But will foo Pointing to another object will report an error
foo = {
} // Report errors TypeError: "foo" is read-only
ES6 Six ways to declare variables
stay ES5 in , There are only two ways to declare variables ,var and function command .ES6 Except for the addition of let and const command , There are two other ways to declare variables : import and class command .
Properties of the top-level object
Top objects , In the browser environment, it refers to window object , stay Node The middle finger is global object .ES5 in , The properties of the top-level object are equivalent to the global variables
window.a = 5
console.log(a) //5
b = 2
console.log(window.b) //2
stay ES6 in ,var and function Global variables declared by the command , Still top-level object properties , but let,const,class The global variable of command life does not belong to the property of the top-level object .
var a = 1
//node Medium is global.a
console.log(window.a) //1
let b = 2
console.log(window.b) //undefined
版权声明
本文为[Xiao Shen Yue]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204212156117733.html
边栏推荐
- 测试用例和设计方法
- Hard core strength, recognized by many parties | cloud expansion technology, as the core manufacturer of RPA, was selected into the 2022 China RPA procurement guide
- IDEA通过Jedis操作Linux上的Redis;Failed to connect to any host resolved for DNS name问题
- ISMAR 2022 journal paper (tvcg) contribution exchange
- [UML operation contract]
- 【最佳实践】巡检项:云服务器(CVM)实例本地盘类型检查
- UML integrated design example
- MSWEP数据nc格式转tif格式
- Lenovo announced the new progress of ESG: it promised that 100% of all computer products would contain recycled plastics by 2025
- 【VSCode】调试器debugger详细使用手册
猜你喜欢

软件测试流程与测试模型

Helm installation sonarqube (bitnami) 9.3

联想公布ESG新进展:承诺2025年全线计算机产品100%含有再生塑料
![[charming Java] - data types and variables](/img/d1/22122803b7b796fbc5e269219d6db8.png)
[charming Java] - data types and variables

mysql 模糊搜索与校对规则

Seven schemes of implementing distributed lock based on redis

【VSCode】调试器debugger详细使用手册

【JVM】10道不得不会的JVM面试题

js实现公告自动滚动

Use try-with-resources or close this “FileOutputStream“
随机推荐
Huayun actively responded to the anti epidemic call of Hefei high tech Zone: practicing social responsibility and contributing to the strength of science and technology enterprises
测试用例和设计方法
redis配置文件详解
ISMAR 2022 journal paper (tvcg) contribution exchange
外包学生管理系统架构设计文档
How to set the South parameter when streaming from libvlc library
[JVM] 10 interview questions
EventBridge 集成云服务实践
分析师认为三星Galaxy Z Fold 4和Z Flip 4可能比其前代产品更便宜
Unity3d C uses the offset of material map to realize the function of unlimited moving background effect of 2D game single background image (including source code)
Browser principle interview questions
Leetcode0785. 判断二分图(medium,二分图,DFS)
在線CSV轉YAML工具
echart 写一个大屏展示圆边渐变柱状图
Interview must brush algorithm top101 knapsack nine lectures Top13
ServiceWorker 缓存与 HTTP 缓存
【WebGIS】WebGIS、桌面GIS、移动GIS、三维GIS的简介
Analysts believe that Samsung Galaxy Z fold 4 and Z flip 4 may be cheaper than their previous products
JVM自定义类加载器在代码扩展性的实践
Thread safety for the first time. This article is enough