基础语法
function() {} 相当于 ()=>{}
let fun1 = function(item){
return item;
}
相当于
let fun2 = item => item;
箭头函数可以根据参数个数来省略(),可以根据函数体内部代码的行数来省略{}
- 一个参数时,可以省略()
item => {} (右侧使用大括号时,需要手动设置ruturn,如果右侧没有大括号则是return的值) - 不要参数或者多个参数时,不可以省略()
() => {}
(item,index) => {}
let arr = [{
name:'xpf',
gender:'male'
},{
name:'tom',
gender:'male'
},{
name:'xiaohong',
gender:'female'
}]
let res1 = arr.filter(function(item){
return item.gender == 'female';
})
let res2 = arr.filter( (item)=>{
return item.gender == 'female';
} )
console.log(res1);
console.log(res2);
案例二
let obj = {
name:'xpf',age:25,
sayName:()=>{
console.log(this.name);
},
sayAge:function(){
console.log(this.age);
}
}
obj.sayName(); // undefined
obj.sayAge(); // 25
注意: 注意:箭头函数中没有this,this指向该箭头函数的外部(父类)函数。(声明时确定,call和apply不能修改this的值)如果箭头函数外部没有函数,那么这个this就指向全局对象
案例三
let obj = {
list:[1,2,3,4],
add(){
this.list.forEach(function(){
console.log(this.list); // undefined
})
}
}
obj.add();
解决方案一:手动更改this
let obj = {
list:[1,2,3,4],
add(){
var that = this;
this.list.forEach(function(){
console.log(that.list)
})
}
}
obj.add();
解决方案二:使用箭头函数
let obj = {
list:[1,2,3,4],
add(){
this.list.forEach(()=>{
console.log(this.list)
})
}
}
obj.add();
箭头函数的this先指向了外部的add函数,由于add函数被obj对象调用,所有add方法中的this指向了obj, 最终,箭头函数中的this指向了obj