当前位置:网站首页>ES6学习-- LET
ES6学习-- LET
2022-06-25 21:50:00 【攀登程序猿】
特点
(1)变量声明不能重复
(2)变量具有块级作用域
(3)变量不存在变量提升,即先使用后声明
(4) 不影响作用链
特点案例:
(1)变量声明不能重复,重复时报错,停止脚本 Uncaught SyntaxError: Identifier 'b' has already been declared
// 变量声明不能重复
var a = 0
var a = 10
console.log(a)
// 不加下面的内容时,此处可以输出,添加下面的内容时输出为b has already been declared,连10都不会输出了
let b = 10;
let b = 11;
console.log(b)
//Uncaught SyntaxError: Identifier 'b' has already been declared
(2)块级作用域
// 块级作用域
{
var testBlockVar = '测试块';
let testBlockLet = '测试块';
}
console.log(testBlockVar)
console.log(testBlockLet)
回显如下,此处前面的是可以执行的,let冲突的时候是都不会执行
(3)变量提升 -- 未声明变量之前直接使用
console.log(testUpLet)
console.log(testUpVar)
var testUpVar = '测试变量提升';
let testUpLet = '测试变量提升'注:let可以在声明之前使用,值为undefined,let的会报错,并且在报错的地方直接停止程序

(4)不影响作用链 -- 会向上找let的变量
{
let testGlobal = '尚硅谷外';
let testGlobal1 = '尚硅谷1'
function f() {
let testGlobal = '尚硅谷内';
console.log(testGlobal)
console.log(testGlobal1)
}
f();
}会向上寻找变量,如果内部定义一个相同的变量,则使用自己同级的变量

典型问题
(1)let修改块作用域
<!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">点击切换颜色</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'; // 正确写法
items[i].style.backgroundColor = 'pink' // 错误写法,会抛出 Cannot read properties of undefined (reading 'style') at HTMLDivElement.items.<computed>.onclick
}
}
// 错误的原因解析如下,因为function在click的时候才去执行,此时i的值是全局的,已经变成了3,因此找不到items[3],修改成let时,点击时,会找自己的块,如下的每个块,function中没有,则找到块内的上面,let i = 0/1/2/3
{
var i = 0;
items[0].onclick = function () {
// this.style.backgroundColor = 'pink'; // 正确写法
items[i].style.backgroundColor = 'pink' // 错误写法,会抛出 Cannot read properties of undefined (reading 'style') at HTMLDivElement.items.<computed>.onclick
}
}
{
var i = 1;
items[1].onclick = function () {
// this.style.backgroundColor = 'pink'; // 正确写法
items[i].style.backgroundColor = 'pink' // 错误写法,会抛出 Cannot read properties of undefined (reading 'style') at HTMLDivElement.items.<computed>.onclick
}
}
{
var i = 2;
items[2].onclick = function () {
// this.style.backgroundColor = 'pink'; // 正确写法
items[i].style.backgroundColor = 'pink' // 错误写法,会抛出 Cannot read properties of undefined (reading 'style') at HTMLDivElement.items.<computed>.onclick
}
}
{
var i = 3;
items[3].onclick = function () {
// this.style.backgroundColor = 'pink'; // 正确写法
items[i].style.backgroundColor = 'pink' // 错误写法,会抛出 Cannot read properties of undefined (reading 'style') at HTMLDivElement.items.<computed>.onclick
}
}
</script>
</body>
</html>(2)上面案例闭包修改
注:可以看出立即执行函数会形成一个自己的封闭空间,其不会被外部的其他变量影响,其实这个如果再有一个return的话就是一个标准的闭包了。
<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>闭包函数拆解开,类似于下图,可以看出,传参在函数内部有自己的作用域,i已经不在使用for循环的块级域。
<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)如果闭包不传参,使用全局参数var呢
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)很明显了,和上面的一样,每次for循环已经把i的值加到了4,后续点击的时候setOnclick没有传参,使用全局参数i = 4
类似案例如下:
//情况1
//闭包函数的外部函数没有初值
var i = 0; //全局变量
function outerFn(){
function innnerFn(){
i++;
console.log(i);
}
return innnerFn;
}
var inner1 = outerFn(); //闭包函数的外部函数也没有初值,用的全局变量
var inner2 = outerFn();
//两个函数共用同一个全局变量
inner1(); //1
inner2(); //2
inner1(); //3
inner2(); //4
//情况2
//闭包函数的外部函数有初值
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)终极问题 -- 计程车问题
暂时没看懂此问题容易出错的在哪,后续补充
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))
边栏推荐
- 哪些PHP开源作品值得关注
- How to disable the optical drive
- 27 Chinese scholars including Yaoban and chendanqi from Tsinghua won the awards, and the list of winners of Sloan award in 2022 was issued
- Leetcode topic [array] -18- sum of four numbers
- MATLAB Programming Notes
- 2022-2028 global industrial TFT LCD industry survey and trend analysis report
- 2022-2028 global selective laser sintering service industry research and trend analysis report
- Research and Analysis on the current situation of China's magnetic detector Market and forecast report on its development prospect (2022)
- 聊聊Adapter模式
- Hello, teacher, is it really safe to open an account in Alipay fund?
猜你喜欢

2022-2028 global horizontal reciprocating compressor industry research and trend analysis report

Three layer architecture + routing experiment

oracle -- 表操作

2022-2028 global industrial touch screen industry research and trend analysis report

2022-2028 global vacuum jacket system industry survey and trend analysis report

Zhihu Gaozan: what ability is important, but most people don't have it?

腾讯《和平精英》新版本将至:新增账号安全保护系统,游戏内违规行为检测升级

Facing the "industry, University and research" gap in AI talent training, how can shengteng AI enrich the black land of industrial talents?
![[intensive lecture] 2022 PHP intermediate and advanced interview questions (II)](/img/50/c9572beaa035d5e6e78a57fcd1302c.jpg)
[intensive lecture] 2022 PHP intermediate and advanced interview questions (II)

Why absolute positioning overlaps
随机推荐
2022-2028 global horizontal reciprocating compressor industry research and trend analysis report
Unity技术手册 - 生命周期内颜色ColorOverLifetime--速度颜色ColorBySpeed
2022-2028 global DC linear variable differential transformer (LVDT) industry survey and trend analysis report
Dio encapsulated by the flutter network request (cookie management, adding interceptors, downloading files, exception handling, canceling requests, etc.)
Exclusive interview with deepmindceo hassabis: we will see a new scientific Renaissance! AI's new achievements in nuclear fusion are officially announced today
2022爱分析· IT运维厂商全景报告
Jingwei Hengrun is registered through the science and Innovation Board: it plans to raise 5billion yuan, with a 9-month revenue of 2.1 billion yuan
MATLAB Programming Notes
Interview shock 23: talk about thread life cycle and transformation process?
简单好用的缓存库 gcache
Global and Chinese oleic acid operation mode and market supply and demand forecast report 2022 ~ 2028
Why is BeanUtils not recommended?
目前期货怎么开户安全些?哪些期货公司靠谱些?
How to open a futures account safely at present? Which futures companies are more reliable?
Research Report on China's new energy technology and equipment market competition analysis and marketing strategy suggestions 2022-2028
Market depth analysis and development strategy consulting report of China's fire equipment market 2022-2028
Privatization lightweight continuous integration deployment scheme -- 03 deployment of Web services (Part 2)
Market demand analysis and investment prospect research report of China's CNC machine tool industry 2022-2028
CVPR2022教程 | 马里兰大学《机器学习遥感处理:农业与粮食安全》教程
China coated abrasive tools industry market depth analysis and development strategy consulting report 2022-2028