Day03·ES6新增语法
-
定义变量时let/const和var的区别:
1) 新增了一个块级作用域;
if(ture){
var n=1;
}
console.log(n);//1
if(ture){
let i=10;
}
console.log(i);// i is not defined报错类型:未定义
2) 没有变量的默认提升;
//有提升功能
console.log(n);//undefined
var n=1;//未赋值的变量提升至顶部
//没有提升功能
console.log(i);// Cannot access ‘i’ before initialization报错:初始化前无法访问"i"
let i=10;
3) 同一变量不能重复定义;
var n=1;
var n=2;
console.log(n);//2
let i=10;
let i=20;
console.log(i);// Identifier ‘i’ has already been declared报错:变量"i"已被声明
4) 定义的变量不会自动挂载到window对象上;
var n=1;
console.log(window.n);//1
let i=10;
console.log(window.i);//undefined
5) 存在暂时性死区(必须定义后才能使用);
var n=1;
if(ture){
n=2;
console.log(n);// Cannot access ‘n’ before initialization报错:初始化前无法访问"n"
let n=10;
}
6) let和const的区别:const定义常量用(定义后常量不可更改); -
字符串模板:(用
插入字符${变量}
语法代替 “插入字符”+变量 语法) -
数据结构:(将复杂结构中的内容结构成一个简单的结构)
let student{
name:”李四”,
age:21
}
let{name,age}=student;
console.log(name);//李四
console.log(age);//21 -
对象的简化写法:
-
箭头函数:
① 语法:用变量定义 --> let a=()=>{}
简写:a. 如果只有一个参数,可以省略小括号;
b. 如果有且仅有一个return语句,可以省略return和花括号;
let a=(n)=>{
return nn; --> let a=n=>nn;
}
② function函数和箭头函数的区别:
-
this的指向性问题:(function中指向运行环境;箭头函数中永远指向生产环境);
-
无提升功能;
show();//window
function show(){
console.log(this);
};
show();//Cannot access ‘show’ before initialization未定义报错
let show=()=>{
console.log(this);
} -
因为this指向固定,所以不能作为构造函数使用;
-
没有arguments参数集合;(可以用拓展运算符(…)实现相似方法);
b. arguments是js中默认的属性;拓展运算符需手动加入;
③ 案例:
</div>
<script>
//需求:点击div时,三秒后背景色变成红色
let box=document.getElementsByClassName("box")[0]
box.onclick=function(){
//1)延时定时器 ,异步操作 window环境下调用所以this指向window,可以用暂时性保存变量的方法如下代码:
var that=this;
setTimeout({
console.log(that)
that.style.background="red"
},3000)
// 2)用箭头函数固定this指向的方法:this永远指向它的生产环境即box事件编程中,所以this就永远指向了box;如下代码:
setTimeout(function(){
console.log(this)
this.style.background="red"
},3000)
}
//箭头函数:如果业务中的this指向性,不想发生变化时使用箭头函数;
</script>