案例一 、点击盒子变色
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
div {
width: 200px;
height: 200px;
background-color: pink;
}
</style>
</head>
<body>
<div id="ad"></div>
<script>
// 点击div两秒后变色
let ad = document.getElementById('ad')
ad.addEventListener('click',function() {
setInterval(() => {
this.style.background = 'purple'
}, 2000)
})
</script>
</body>
</html>
为什么箭头函数的this就好使而function中的this不好使呢?
- 因为function中的this指向的是window,window没有style属性
- 解决function的this指向问题要在外侧加入 let _this=this 保存外层this
而箭头函数的this是静态的,指向声明时所在函数的this值。计数器里面的this指向外部函数,外部函数的this指向事件源ad
案例二 、筛选偶数
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
</style>
</head>
<body>
<script>
// 从数组中返回偶数元素
const arr = [1, 2, 4, 5];
const result = arr.filter(item => item % 2 === 0)
console.log(result)
</script>
</body>
</html>
总结:箭头函数适合与 this 无关的回调,比如定时器、数组的方法回调;不适合与 this 有关的回调,比如事件回调,对象的方法