当前位置:网站首页>ES6 learning -- let
ES6 learning -- let
2022-06-25 23:02:00 【Climbing procedural ape】
characteristic
(1) Variable declarations cannot be repeated
(2) Variable has block level scope
(3) The variable does not exist , That is, use first and then declare
(4) Does not affect the chain of action
Characteristic cases :
(1) Variable declarations cannot be repeated , Repeat and make mistakes , Stop script Uncaught SyntaxError: Identifier 'b' has already been declared
// Variable declarations cannot be repeated
var a = 0
var a = 10
console.log(a)
// Without the following , Here you can output , When you add the following, the output is b has already been declared, even 10 Will not output
let b = 10;
let b = 11;
console.log(b)
//Uncaught SyntaxError: Identifier 'b' has already been declared
(2) Block level scope
// Block level scope
{
var testBlockVar = ' Test block ';
let testBlockLet = ' Test block ';
}
console.log(testBlockVar)
console.log(testBlockLet)
Echo as follows , The previous one here is executable ,let When there is a conflict, it will not be implemented
(3) Variable Promotion -- Use directly before declaring variables
console.log(testUpLet)
console.log(testUpVar)
var testUpVar = ' Test variable promotion ';
let testUpLet = ' Test variable promotion '
notes :let Can be used before declaration , The value is undefined,let Will report a mistake , And stop the program directly where the error is reported
(4) Does not affect the chain of action -- Will look up let The variable of
{
let testGlobal = ' Outside shangsilicon Valley ';
let testGlobal1 = ' Silicon Valley 1'
function f() {
let testGlobal = ' In Silicon Valley ';
console.log(testGlobal)
console.log(testGlobal1)
}
f();
}
Will look up for variables , If you internally define the same variable , Then use its own sibling variables
Typical problems
(1)let Modify block scope
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.item {
height: 50px;
width: 50px;
border: 1px solid black;
display: inline-block;
}
</style>
</head>
<body>
<div class="pageheader"> Click to switch colors </div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<script>
let items = document.getElementsByClassName('item')
for (var i = 0; i < items.length; i++) {
items[i].onclick = function () {
// this.style.backgroundColor = 'pink'; // Write it correctly
items[i].style.backgroundColor = 'pink' // Wrong writing , Will throw out Cannot read properties of undefined (reading 'style') at HTMLDivElement.items.<computed>.onclick
}
}
// The cause of the error is analyzed as follows , because function stay click Only when it's time to execute , here i The value of is global , Has become 3, So we couldn't find items[3], Modified into let when , Clicking time , I will find my own piece , Each of the following blocks ,function There is no , Then find the top in the block ,let i = 0/1/2/3
{
var i = 0;
items[0].onclick = function () {
// this.style.backgroundColor = 'pink'; // Write it correctly
items[i].style.backgroundColor = 'pink' // Wrong writing , Will throw out Cannot read properties of undefined (reading 'style') at HTMLDivElement.items.<computed>.onclick
}
}
{
var i = 1;
items[1].onclick = function () {
// this.style.backgroundColor = 'pink'; // Write it correctly
items[i].style.backgroundColor = 'pink' // Wrong writing , Will throw out Cannot read properties of undefined (reading 'style') at HTMLDivElement.items.<computed>.onclick
}
}
{
var i = 2;
items[2].onclick = function () {
// this.style.backgroundColor = 'pink'; // Write it correctly
items[i].style.backgroundColor = 'pink' // Wrong writing , Will throw out Cannot read properties of undefined (reading 'style') at HTMLDivElement.items.<computed>.onclick
}
}
{
var i = 3;
items[3].onclick = function () {
// this.style.backgroundColor = 'pink'; // Write it correctly
items[i].style.backgroundColor = 'pink' // Wrong writing , Will throw out Cannot read properties of undefined (reading 'style') at HTMLDivElement.items.<computed>.onclick
}
}
</script>
</body>
</html>
(2) The closure of the above case is modified
notes : It can be seen that immediately executing the function will form its own closed space , It will not be affected by other external variables , In fact, if there is another one return It is a standard closure .
<script>
let items = document.getElementsByClassName('item')
for (var i = 0; i < items.length; i++) {
(function (i) {
items[i].onclick = function () {
items[i].style.backgroundColor = 'pink';
}
})(i)
}
</script>
The closure function is disassembled , Similar to the following picture , It can be seen that , Parameter passing has its own scope inside the function ,i No longer in use for Block level domain of the loop .
<script>
let items = document.getElementsByClassName('item')
function setOnclick(i) {
items[i].onclick = function () {
items[i].style.backgroundColor = 'pink';
}
}
for (var i = 0; i < items.length; i++) {
setOnclick(i)
}
</script>
(3) If the closure does not pass parameters , Use global parameters var Well
let items = document.getElementsByClassName('item')
var i = 0;
function setOnclick() {
items[i].onclick = function () {
console.log(i)
items[i].style.backgroundColor = 'pink';
}
}
for (var i = 0; i < items.length; i++) {
setOnclick()
}
console.log(i)
Obviously the , It's the same as up here , Every time for The cycle has put i The value of is added to 4, When you click next setOnclick There is no reference , Use global parameters i = 4
Similar cases are as follows :
// situation 1
// The outer function of a closure function has no initial value
var i = 0; // Global variables
function outerFn(){
function innnerFn(){
i++;
console.log(i);
}
return innnerFn;
}
var inner1 = outerFn(); // The outer function of the closure function also has no initial value , Global variables used
var inner2 = outerFn();
// Two functions share the same global variable
inner1(); //1
inner2(); //2
inner1(); //3
inner2(); //4
// situation 2
// The outer function of a closure function has an initial value
function outerFn(){
var i = 0;
function innnerFn(){
i++;
console.log(i);
}
return innnerFn;
}
var inner1 = outerFn();
var inner2 = outerFn();
inner1(); //1
inner2(); //1
inner1(); //2
inner2(); //2
(4) The ultimate question -- Taxi problem
I don't understand where this problem is prone to error , Subsequent complement
let car = (function () {
let start = 12
let total = 0
return {
price(n) {
if (n <= 3) {
total = start;
} else {
total = start + (n - 3) * 5
}
return total
},
jam(flag) {
return flag ? total + 10 : total;
}
}
})()
console.log(car.price(3))
console.log(car.jam(true))
console.log(car.jam(false))
Reference material : Silicon Valley Web front end ES6 course , cover ES6-ES11
边栏推荐
- 2022-2028 global selective laser sintering service industry research and trend analysis report
- Simple and easy-to-use cache library gcache
- 2022年河南省第一届职业技能大赛网络安全项目试题
- Eureka core ⼼ source code analysis
- 【EOSIO】EOS/WAX签名错误 is_canonical( c ): signature is not canonical 问题
- 关闭MongoDB一些服务需要注意的地方(以及开启的相关命令)
- Civil Aviation Administration: by 2025, China will initially build a safe, intelligent, efficient and green aviation logistics system
- 2022爱分析· IT运维厂商全景报告
- Analysis report on demand and investment forecast of global and Chinese flame retardant hydraulic oil market from 2022 to 2028
- Unity技术手册 - 生命周期旋转RotationOverLifetime-速度旋转RotationBySpeed-及外力
猜你喜欢
2、一个向量乘它的转置,其几何意义是什么?
Utilisation de la classe Ping d'Unity
Programmer weekly (issue 4): the wealth view of programmers
使用EAST ocr遇到的坑解决方法(编译lanms)
Fastjson反序列化随机性失败
1281_FreeRTOS_vTaskDelayUntil实现分析
记|一次exists关键字的学习记录
2022-2028 global selective laser sintering service industry research and trend analysis report
Lecture 14 of the Blue Bridge Cup -- number theory [exercises]
Wpewebkit debugging MSE playback
随机推荐
Global and Chinese oleic acid operation mode and market supply and demand forecast report 2022 ~ 2028
2022-2028 global SiC igniter industry research and trend analysis report
Jz-064- maximum value of sliding window
EVC, VVC, lcevc test: how about the performance of the latest MPEG codec?
The wisdom of questioning? How to ask questions?
简单好用的缓存库 gcache
Unity技术手册 - GetKey和GetAxis和GetButton
Glory launched the points mall to support the exchange of various glory products
Talk about adapter mode
不荒唐的茶小程序-规则改动
2022-2028 global iridium electrode industry research and trend analysis report
2022-2028 global extrusion coating and lamination production line industry research and trend analysis report
Lecture 14 of the Blue Bridge Cup -- number theory [exercises]
Does jQuery cache any selectors- Does jQuery do any kind of caching of “selectors”?
HotSpot JVM 「01」类加载、链接和初始化
ES6 -- 形参设置初始值、拓展运算符、迭代器、生成函数
使用EAST ocr遇到的坑解决方法(编译lanms)
提问的智慧?如何提问?
Raspberry PI (bullseye) replacement method of Alibaba cloud source
zabbix_server配置文件详解