需求一:点击div 2秒之后改变div背景颜色
传统写法存在的问题:
<style>
div{
width: 200px;
height: 200px;
border: 1px solid #f3f3f3;
background: #f5f5f5;
color: pink;
text-align: center;
line-height: 200px;
}
</style>
<!-- 点击一个盒子两秒之后变色 -->
<div id="divId">
我是一个盒子
</div>
this
指向window
而不是指向divId
元素
// 创传统写法的问题
// 1 获取元素
let cdiv = document.getElementById("divId")
cdiv.addEventListener("click",function(){
setTimeout(function(){
console.log(this);
// this 指向window
this.style.background = "pink"
// 报错:TypeError: Cannot set properties of undefined (setting 'background')
},2000)
})
传统写法的解决方案:
提前保存this
的值
let cdiv = document.getElementById("divId")
cdiv.addEventListener("click",function(){
// 传统写法
// 提前保存this的值
let that = this
setTimeout(function(){
console.log(that);
// that 指向divId元素
that.style.background = "red"
},2000)
})
使用ES6写法:
let cdiv = document.getElementById("divId")
//这里的function不能使用箭头函数否则this还是指向window
cdiv.addEventListener("click",function(){
//计时器使用箭头函数 this指向divId元素
setTimeout( () => this.style.background="pink",2000)
})
需求二:从数组中返回偶数的元素:
// 从数组中返回偶数的元素
const arr = [1,2,5,87,6759,890,456,29,213,34]
const result = arr.filter(item=>item%2==0)
console.log(result);
// [2, 890, 456, 34]
总结:
- 箭头函数适合与 this 无关的回调、定时器、数组的方法回调
- 箭头函数不适合与 this 有关的回调、 事件回调、 对象的方法