1.箭头函数是用来简化函数定义语法的
const fn = () => {
console.log(123);
}
fn();
2.在箭头函数中 函数体中只有一句代码,且代码的执行结果就是返回值,可以省略大括号
function sum(n, m) {
return n + m;
}
const newSum = (a, b) => a + b;
console.log(sum(1, 2));
console.log(newSum(1, 2));
3.在箭头函数中 如果形参只有一个,可以省略小括号
const fn = value => value++;
4.不能作为构造实例化对象
// let Person = (name, age) => {
// this.name = name;
// this.age = age;
// }
// let me = new Person('yy', 18);
// console.log(me);
5.3.不能使用 arguments 变量
// let fn = () => {
// console.log(arguments);
// }
// fn(1, 2, 3);
6.this 是静态的,this始终指向函数声明时所在作用域下的this的值,如果在箭头函数中使用this this关键字将指向箭头函数定义位置中的this
function getName() {
console.log(this.name);
}
let getNewName = () => console.log(this.name);
//设置window 对象的 name 属性
window.name = 'YY';
const obj = {
name: '张三'
}
//直接调用
getName();
getNewName();
//call方法调用
getName.call(obj);
getNewName.call(obj);
7.小案例
(1) 定时器,1秒后div盒子变成红色
<div></div>
let div = document.getElementsByTagName('div')[0];
div.onclick = function() {
setTimeout(() => this.style.background = 'red', 1000);
}
(2)从数组中返回偶数的元素
const arr = [1, 2, 3, 4, 56, 8, 64, 7]
// 传统写法
// const result = arr.filter(function(item) {
// if (item % 2 === 0) {
// return true;
// } else {
// return false;
// }
// })
const result = arr.filter(item => item % 2 === 0)
console.log(result);
总结: ①箭头函数适合与this无关的回调,定时器,数组的方法回调 ② 箭头函数不适合与this有关的回调,事件回调,对象的方法