当前位置:网站首页>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))
边栏推荐
- APP-新功能上线
- Raspberry PI (bullseye) replacement method of Alibaba cloud source
- Market demand analysis and investment prospect research report of China's CNC machine tool industry 2022-2028
- ES6-- 集合
- ES6-- 模板字符串、对象的简化写法、箭头函数
- 民航局:到 2025 年我国将初步建成安全、智慧、高效和绿色的航空物流体系
- How to design a complex business system? From the understanding of domain design, cloud native, micro service, and middle platform
- ES6 -- 形参设置初始值、拓展运算符、迭代器、生成函数
- AbstractFactory Abstract Factory
- How to use the find command
猜你喜欢

Nacos 源码分析01 代码结构

2022-2028 global SiC igniter industry research and trend analysis report

面对AI人才培养的“产学研”鸿沟,昇腾AI如何做厚产业人才黑土地?
Data annotation in the second half: growth flywheel under PLG mode Manfu Technology

不荒唐的茶小程序-规则改动

Cvpr2022 tutorial | machine learning remote sensing processing: agriculture and food security, University of Maryland

2022爱分析· IT运维厂商全景报告

Why absolute positioning overlaps

Three layer architecture + routing experiment

Obsidian basic tutorial
随机推荐
Obsidian basic tutorial
ES6 -- 形参设置初始值、拓展运算符、迭代器、生成函数
Zero Trust: break the passive development mode of "attack and defense" and build a "moat" for enterprise safety
Some reflections on preparing for the Blue Bridge Cup
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
Dio encapsulé pour les requêtes réseau flutter (gestion des cookies, ajout d'intercepteurs, téléchargement de fichiers, gestion des exceptions, annulation des requêtes, etc.)
2022-2028 global cloud based remote browser isolation industry research and trend analysis report
Market demand analysis and investment prospect research report of China's CNC machine tool industry 2022-2028
[WPF] XAML code skills that can be directly used for converting CAD engineering drawings to WPF
Touring band: a 5g based multi camera remote distributed video production experiment
Simple and easy-to-use cache library gcache
Intimacy - [comfortable exit] - final communication to reduce injury
MySQL数据库索引
Obsidian basic tutorial
Data annotation in the second half: growth flywheel under PLG mode Manfu Technology
Does jQuery cache any selectors- Does jQuery do any kind of caching of “selectors”?
2022-2028 global DC linear variable differential transformer (LVDT) industry survey and trend analysis report
Unity技术手册 - 生命周期旋转RotationOverLifetime-速度旋转RotationBySpeed-及外力
2022-2028 global proton exchange membrane hydrogen electrolyzer industry survey and trend analysis report
Tiger DAO VC产品正式上线,Seektiger生态的有力补充