ES6-箭头函数的实践与应用场景
案例
2秒延迟改变盒子的背景颜色
// 之前常用解决方案
let box = document.getElementById("box");
// 绑定事件
box.addEventListener("click", function () {
// 保存this值
let _this = this;
setTimeout(function () {
// 修改指定背景颜色 this
_this.style.backgroundColor = "#ff8";
}, 2000); });
// 箭头函数解决方案
let boxes = document.getElementById("boxes");
// 绑定事件
boxes.addEventListener("click", function () {
setTimeout( () => {
// 修改指定背景颜色 this
this.style.backgroundColor = "#ff8";
},2000); });
数组筛选偶数
const arr=[5,25,8,36,59,17,96];
// 常规方法
const result=arr.filter(function(item){
if(item%2===0){
return true
} })
// 箭头函数
const result=arr.filter(item=>{
if (item%2===0) {
return true
}
})
// 简写
const result=arr.filter(item=>item%2===0)
console.log(result);
//结果:(3) [8, 36, 96]
备注
1.适合与this无关的回调(如:定时器、数组的方法回调)
2.不适合与this有关的回调(如:DOM元素的事件回调、对象的方法