箭头函数的写法
箭头函数的省略问题
如果函数中仅有一句话,并且这句话是return返回,可以省略{}和return
var fn=function(a,b){ var fn=(a,b)=>a+b;
return a+b
}
var fn=function(){ var fn=()=>{
var a=3; var a=3;
var b=4; var b=4;
return a+b; return a+b;
} }
var arr=[1,2,3,4,5];
省略的两种情况
箭头函数中如果仅有一个参数可以省略小括号
如果没有参数,或者有一个以上的参数不能省略小括号
var bool=arr.every(function(item){
return item>0
})
if(arr.every(item=>item>0));
arr.filter(item=>item>3)
var sum=arr.reduce((value,item)=>value+=item)
setInterval(()=>{
},16)
var obj={
a:function(){
ES5的方法
},
b(){
ES6的方法
},
c:()=>{
ES6箭头函数
}
}
更改this指向
var obj={
b:1,
a:function(){
document.obj=this;
document.addEventListener("click",this.clickHandler);
},
clickHandler(e){
document.removeEventListener("click",this.obj.clickHandler)
}
}
当函数换为箭头函数时,this将会被指向当前函数外this的指向
var obj={
b:1,
a:function(){
document.addEventListener("click",e=>this.clickHandler(e));
var fn=(e)=>{
console.log(this);//当函数换为箭头函数时,
// this将会被指向当前函数外this的指向
this.clickHandler(e);
}
//在定义了fn之后监听可以写成
document.addEventListener("click",fn);
},
clickHandler(e){
e.currentTarget为侦听的对象
document.removeEventListener("click",this.clickHandler)
}
}
箭头函数主要可以作为改变函数中this的指向问题
箭头函数中临时起名的问题
var obj={
a:1,
init:function(){
var bn=document.querySelector("button");
//这里的this.fn就是用来临时存储箭头函数的,this.fn就是原来的clickHandler。
e就是箭头函数的参数,this.clickHandler(e) 就是实际要执行的函数,可以加上任意多个参数
bn.addEventListener("click",this.fn=e=>this.clickHandler(e));
},
clickHandler:function(e){
console.log(this.a);
e.currentTarget.removeEventListener("click",this.fn);
//所以这里移除侦听的函数名就是this.fn
}
}
this指向
1、对象函数中,this是当前对象
2、事件侦听的函数中,this是侦听事件的对象
3、回调函数,this是window
4、箭头函数中的this,this是箭头函数外this的指向