ES之 02.箭头函数
索引
基本规则
- 删掉一个function关键字
- 多个参数,分隔
- 没有参数加括号
- 1个参数可选择(括号的有无)
const numbers=[5,6,13,0,1,2]
const double=numbers.map(function (number) {
return 2*number;
})
//1个参数时可带括号或者不带括号
const double1=numbers.map((number)=>{
return 2*number;
})
const double2=numbers.map(number=>{
return 2*number
})
//隐式返回
const double3=numbers.map((number)=>2*number);
//大于1个参数
const double4=numbers.map((number,i)=>`${i}:${number}`)
//无任何参数
const double5=numbers.map(()=>`hello`)
匿名函数
const greet=(name)=>{
console.log(`hello ${name}`)
}
greet("hk")
箭头函数的this指向
- 箭头函数无自己的this,this继承自父作用域
- 词法作用域(定义时指定而非运行时指定)
const Jelly={
name:'Jelly',
hobbies:["coding","music",'reading'],
printHobbies:function(){
//console.log(this);//指向Jelly对象
this.hobbies.map(function(hobby){
//console.log(this) //这个函数独立调用时this指向window
console.log(`${this.name} loves ${hobby}`); //这里的this.name为空的
})
}
}
Jelly.printHobbies()
//传统修改
const Jelly1={
name:'Jelly',
hobbies:["coding","music",'reading'],
printHobbies:function(){
const self=this;
this.hobbies.map(function(hobby){
console.log(`${self.name} loves ${hobby}`);
})
}
}
Jelly1.printHobbies();
//ES6里
const Jelly2={
name:'Jelly',
hobbies:["coding","music",'reading'],
printHobbies:function(){
this.hobbies.map(hobby=>{
console.log(`${this.name} loves ${hobby}`);
})
}
}
Jelly2.printHobbies();
不宜使用的场景
1.作为构造函数,一个方法需要绑定到对象
const Person=function (name,points) {
this.name=name
this.points=points;
}
const Person1=(name,points)=>{
this.name=name
this.points=points;
}
const p=new Person('hk',100)
//const p1=new Person1('hk1',90);//Uncaught TypeError: Person1 is not a constructor
Person.prototype.updatePoints=()=>{
console.log(this) //指向window
this.points++
}
2.当真的需要this的时候
const button=document.querySelector(".zoom")
button.addEventListener("click",function(){ //这里不该使用箭头函数
this.classList.add('roate');
setTimeout(()=>{ //这里需要继承上级的this所以用箭头函数
this.classList.remove('roate')
},2000)
})
3.需要arguments对象时
const sum=function(){ //如果写成箭头函数,没有arguments对象报错
return Array.from(arguments).reduce(
(preSum,value)=>preSum+value,0
)
}
//array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

浙公网安备 33010602011771号