es6 箭头函数实践

箭头函数实践

<!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>
posted @ 2021-06-21 11:29  胡勇健  阅读(44)  评论(0)    收藏  举报