2. Var has no block-level scope, but let has (block-level scope includes {} conditional loops, etc.)
3. There is no variable promotion for let (var has, that is, before using it, it will find the declaration of the variable in the code, regardless of the position)
4. Does not affect the scope chain
<script>
{
let name="paopao";
function say(){
console.log(name);
}
say();
}
</script>
5. An example: switching colors
<script>
let items = document.getElementsByClassName('item');
for (var i = 0; i < items.length; i++) {
items[i].onclick = function () {
this.style.background = 'pink';
}//用this不要紧,但是发现用items[i]会报错,因为var是全局的,但是用let就可以
for (let i = 0; i < items.length; i++) {
items[i].onclick = function () {
items[i].style.background = 'pink';
}
}
</script>
<script>
let str = `泡泡
果果
`;
console.log(str);//可以换行,''和""就不行
</script>
${variable name}
<script>
let love="果果";
let obj=`${love}和泡泡`;
console.log(obj);
</script>
Simplify objects
Member variables and member functions can be written directly, and the method can omit the function keyword
<script>
let name="红";
let play=function(){
console.log("吹泡泡");
}
const Guo={
name,
play,//直接放变量名
eat(){
console.log("吃绿绿");
}//省略function
}
</script>
Arrow function
Precautions:
1. Can not be used as a constructor to instantiate objects, only constructor
2. The arguments variable cannot be used
3. When there is only one formal parameter, the middle () can be omitted
4. When there is only one statement in the code body, omit {} (the return statement is also omitted at this time, and the execution result is the return value)
let fn=(a,b)=>{
return a+b;
}
//this是静态的始终指向函数声明时的作用域下的this的值
<script>
function getName1() {
console.log(this.name);
}
let getName2 = () => {
console.log(this.name);
}
window.name = "泡泡";
const school = {
name: "果果"
}
getName1.call(school); //call方法可以改变this的值,指向school
getName2.call(school); //输出果果、泡泡,箭头函数依然指向的是全局对象,只能指向函数在声明时所在作用域
let fun = () => {
console.log(arguments);
}
fun(1, 2, 3, 4);//报错argumrnts未定义
</script>
//省略()
let add=n=>{
return n+n;
}
console.log(add(8));
//省略{}
let pow=n=>n*n;
console.log(pow(8));