ES6-箭头函数

1、写法

ES5写法

let fn = function(a,b){
	return a + b;
}
let res = fn(1,2);
console.log(res);	// 3

ES6写法

let fn = (a,b) =>{
	return a + b;
}
let res = fn(1,2);
console.log(res);	// 3

简写: 如果函数体只有一条语句是返回值, 则可以省略return 语句 ;直接写

let fn = (a, b) => a + b;
let res = fn(1,2);
console.log(res);	// 3

简写: 如果参数只有一个,则可以省略 ()

let fn = x => x * x;
let res = fn(3);
console.log(res); // 9

2、箭头函数不能作为构造实例化对象

let Person = (name,age)=>{
    this.name = name;
    this.age = age;
}
let me = new Person('典韦',30);
console.log(me); // 报错:Uncaught TypeError: Person is not a constructor

3、不能使用arguments变量

let fn = () =>{
    console.log(arguments);
}
fn(1,2,3); // 报错:Uncaught ReferenceError: arguments is not defined

4、案例演示

从数组中返回偶数元素 正常写法

let arr = [16,3,8,34,68,100,97];
let res = arr.filter(function(item){
    if(item % 2 == 0){
        return true;
    }else{
        return false;
    }
})
console.log(res); //[16, 8, 34, 68, 100]

箭头函数写法

let res = arr.filter(item => item % 2 === 0);
console.log(res);  //[16, 8, 34, 68, 100]

总结

箭头函数适合与this无关的回调,例如定时器,数组的方法问题

箭头函数不适合与this有关的问题,例如事件回调,对象的方法

posted @ 2022-06-08 20:16  秋弦  阅读(23)  评论(1编辑  收藏  举报