箭头函数的实践与应用场景
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <style> div{ width: 200px; height: 200px; background: #58a; } </style> <body> <div id="ad"></div> </body> <script> // 需求1 点击div2s后颜色变为粉色 let ad=document.getElementById('ad'); ad.addEventListener("click",function(){ // 这样写报错:Cannot set properties of undefined (setting 'background') 因为this指向的window // setTimeout(function(){ // //修改背景颜色 this // this.style.background='pink'; // }) // 解决方案1 // let _this=this; // setTimeout(function(){ // //修改背景颜色 this // _this.style.background='pink'; // }) // 解决方案2 setTimeout(()=>{ //修改背景颜色 this this.style.background='pink'; }) },2000) // 从数组中返回偶数 const arr=[1,4,6,87,34,56]; const result=arr.filter(item=>item%2==0); console.log(result) // 箭头函数适合this无关的回调,定时器,数组的方法回调 // 箭头函数不适合this有关的回调,事件回调,对象的方法 </script> </html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
div{
width: 200px;
height: 200px;
background: #58a;
}
</style>
<body>
<div id="ad"></div>
</body>
<script>
// 需求1 点击div2s后颜色变为粉色
let ad=document.getElementById('ad');
ad.addEventListener("click",function(){
// 这样写报错:Cannot set properties of undefined (setting 'background') 因为this指向的window
// setTimeout(function(){
// //修改背景颜色 this
// this.style.background='pink';
// })
// 解决方案1
// let _this=this;
// setTimeout(function(){
// //修改背景颜色 this
// _this.style.background='pink';
// })
// 解决方案2
setTimeout(()=>{
//修改背景颜色 this
this.style.background='pink';
})
},2000)
// 从数组中返回偶数
const arr=[1,4,6,87,34,56];
const result=arr.filter(item=>item%2==0);
console.log(result)
// 箭头函数适合this无关的回调,定时器,数组的方法回调
// 箭头函数不适合this有关的回调,事件回调,对象的方法
</script>
</html>

浙公网安备 33010602011771号