箭头函数
使用 => 的方式替代了function,使代码更加简短、清晰易读,尤其是极大的简化了回调函数的编写。
普通方式编写函数
function fn(a){
console.log('function:')
return a+1;
}
console.log(fn(1));
使用箭头函数 编写
//箭头函数 编写
const fun = (a) => {
console.log('fun invoked 箭头函数')
return a+2;
}
console.log(fun(8));
箭头函数还极大的简化了回调函数
const arr = [1,2,3,4,5,6,7,8];
const arr1 = arr.filter(function(a){
return a % 2;//只会返回a%2值为1的值
})
console.log(arr1);//[1,3,5,7]
//使用箭头函数
const arr2 = arr.filter(a => a%2);
console.log(arr2);//[1,3,5,7]
箭头函数的this:箭头函数内部是没有this机制,箭头函数中的this,所代表的指向值,是通过向外层查找得来的
const person = {
name : "li",
age : 21,
message : function(){
console.log(this.name + "," +this.age);
}
};
person.message();
给person对象中的message方法中添加一个延时器,使用箭头函数,会发现在这个message()中,this的指向是不同的,在function中,this指向的是person,所以当延时器里需要指向person的this时,我们就可以手动的将person的指向赋给一个变量,此变量的作用也就相当于this了。
//箭头函数
const person = {
name : "zhang",
age : 21,
message : function(){
const _this = this;//function这里this指向的是person
setTimeout(() =>{
//这样需要使用this特定的指向时,使用_this即可
console.log(_this.name + "," + _this.age);
},1000);
}
};
person.message();