es6 箭頭函式實踐
阿新 • • 發佈:2021-06-21
箭頭函式實踐
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>箭頭函式實踐</title>
<style>
div{
width: 200px;
height: 200px;
background-color: pink;
}
</style>
</head>
<body>
<div id="ad">
</div>
<script>
let ad = document.getElementById('ad');
//繫結事件
ad.addEventListener('click',function () {
setTimeout(()=>{
//箭頭函式的this是靜態,屬於宣告處
this.style.backgroundColor = 'red';
},2000)
});
//需求2
const array = [1,3,5,7,34];
// const result = array.filter(function (item) {
// if(item%2===0){
// return true;
// } else {
// return false;
// }
// });
const result = array.filter(item=>item%2===0);
console.log(result);
//箭頭函式適合與this無關的回撥,定時器,陣列的方法回撥
//箭頭函式不適合與this有關的回撥,事件回撥,物件的方法
</script>
</body>
</html>