箭头函数
使用方法
方法一、(必须得有括号)
const numbers=[1,2,5,7,21,132]
const double=numbers.map(function(numbers){
return numbers*2;
});
console.log(double);
const double2=numbers.map((numbers,i)=>
`${i}:${numbers*2}`;);
console.log(double2);
方法二、
const double2=name=>{alert(name)};
double2('123');
箭头函数的this
--this 获取当前的值而不是其他作用域中的值或者是window里的值
const doubles={
name:'jack',
habbies:['food','sleep','ball'],
printhabbies:function(){
this.habbies.map(hobby=>{
console.log(`${this.name} love ${hobby}`)
})
}
}
doubles.printhabbies();
ES6默认值
function multiply(a=5,b=3){
return a*b;
}
multiply(); multiply(2);
multiply(undefined,3); multiply(2,3);
箭头函数不适用场景
1 作为构造函数,一个方法需要绑定到对象
--错误
const Person=(name,age)=>{
this.name=name;
this.age=age;
}
--正确
const Person= function (name,age) {
this.name=name;
this.age=age;
}
const Persons=new Person('123','12');
const Persons=new Person('123','12');
2.真正需要this值
3.使用arguments