箭头函数
ES6允许使用【箭头】(=>)定义函数
声明一个函数
let fn = function(){
}
let fu = (a,b)=>{
return a+b;
}
//调用函数
let result = fu(1,2);
console.log(result);
this是静态的,this始终指向函数声明时所在作用于下的this的值
function getName(){
console.log(this.name);
}
let getName2 = () => {
console.log(this.name);
}
//1.设置window对象的name属性
window.name = 'study';
const school ={
name:"bad"
}
//直接调用
getName();
getName2();
//call 方法调用
getName.call(school);//bad
getName2.call(school);//study
//2.不能作为构造实例化对象
let Person = (name,age) =>{
this.name = name;
this.age = age;
}
let me = new Person('xiao',30);
console.log(me);//报错:Person is not a constructor
//3.不能使用arguments变量
let fu = () => {
console.log(arguments);
}
fn(1,2,3);//报错:arguments is not defined
//4.箭头函数的简写
//1)省略小括号,当形参有且只有一个的时候
let add = n => {
return n+n;
}
console.log(add(9));
//2)省略花括号,当代码体只有一条语句的时候,此时return必须省略
//而且语句的执行结果就是函数的返回值
let pow = n => n*n;
console.log(pow(8));
箭头函数的实践
//需求1 点击div 2s 后颜色变成粉色
//获取元素
let ad = document.getElementById('ad');
//绑定事件
ad.addEventListener('click',function(){
//ES5做法,保存this的值
let _this = this;
//定时器
setTimeout(function(){
_this.style.background = 'pink;
},2000);
//ES6做法
setTimeout(() => {
this.style.background = 'pink;
},2000);
})
//需求2 从数组中返回偶数元素
const arr = [1,6,9,10,100,25];
//ES5
const result = arr.filter(function(item){
if(item % 2 ===0){
return true;
}else{
return false;
}
})
console.log(result);//[6,10,100]
//ES6
const result = arr.filter(item => item % 2 ===0);
console.log(result);//[6,10,100]
-
箭头函数适合与this无关的回调。
例如:定时器,数组的方法回调 -
箭头函数不适合与this有关的回调。
例如:事件回调,对象的方法