箭头函数的实践与应用场景
<!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>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本