let的用法
出现:因为var 的局限性,let 在es6中引入
作用:let用于声明变量,
let的特点
-
变量不能重复声明
//1.变量不能重复声明 let a = 'wanghh' let a = 'lizhling' //报错 //Uncaught SyntaxError: Identifier 'a' has already been declared
-
块儿级作用域,全局,函数,eval(eval方法时js的语言执行器,能将其中的参数按照js语法进行解析执行)
//块儿级作用域,全局,函数,eval(eval方法是js的语言执行器) { let girl = 'lying' } console.log(girl) //报错 //Uncaught ReferenceError: girl is not defined
-
不存在变量提升
//3.不存在变量提升 console.log(song); let song = "念念不忘" //Cannot access 'song' before initialization
此处可以对照var 学习
console.log(song); //undefined var song = "念念不忘" //var 有变量提升,此处代码相当于 var song console.log(song); song = "念念不忘"
-
不影响作用域链
let school = "hadapuzhpngxue" let math = 'a*b' if(true) { console.log(school) //school先在if 中寻找 然后在script 中寻找 function homework(){ console.log("finished "+math) //math 先在homework 中寻找,然后在if中寻找,最后在script下寻找 } homework() //finished a*b }
作用域链指的是 在js编译器在寻找变量时,在最近的作用域中找,如果找不到再在上一级作用域中寻找,依次寻找,直到找到或者不含该变量为止var 与let 的区别
var与 let的区别
-
在只声明变量不赋值时,打印该变量时都是undedined
let hhh console.log(hhh) //undefined hhh = 'hhhhhhhh' var ooo console.log(ooo) //undefined ooo = "oooo"
-
var 变量声明提前,let无
console.log(ooo) //undefined var ooo = "ooo" //相当于 var ooo console.log(ooo) ooo = "ooo"
console.log(hhh) //报错 Uncaught ReferenceError: Cannot access 'hhh' before initialization let hhh hhh = 'hhhhhhhh'
-
let,var 在块儿级作用域的使用(绑定点击事件)
<style> .item{ width: 50px; height: 50px; float: left; margin:0px 10px; border:1px solid black; } </style> <body> <div class = "item"></div> <div class = "item"></div> <div class = "item"></div> <div class = "item"></div> </body>
var item = document.getElementsByClassName("item") for(var i = 0 ; i < item.length ;i++){ item[i].onclick = function(){ console.log(i) //4 item[i].style.background = 'pink' //找不到item[4] //报错:Uncaught TypeError: Cannot read property 'style' of undefined } } //var 提升变量 作用在全局作用域下 //点击事件触发前,编译过程先将事件绑定 //触发事件后,i在全局作用域下找到后,值为4(四次绑定事件后i++,i变为4)
for(let i = 0 ; i < item.length ;i++){ console.log(Date.now()) item[i].onclick = function(){ console.log(i) //4 item[i].style.background = 'pink' } } //let作用域在for循环中,每次执行循环体时,都会将i重置 //且在点击事件发生时,根据作用域链可以知道绑定该事件时i的值
绑定item,div点击变为粉色