0
点赞
收藏
分享

微信扫一扫

箭头函数和普通函数的this应用

修炼之士 2022-02-26 阅读 43
 <script>
        //this 箭头函数没有自己的this指向其父级的this 
        //普通函数被谁调用则this指向谁
        function getName(){
            console.log(this.name);
        }
        let getName2 = ()=>{
            console.log(this.name);//声明环境为全局作用域
        }
        window.name = "windowName";
        const school = {
            name:'小明'
        };
        getName();//windowName
        getName2();//windowName
        getName.call(school);//小明
        getName2.call(school);//windowName

        let ad=document.getElementById('ad');
        ad.addEventListener('click',function(){
            //1.函数this
            // let _this=this;
            // setTimeout(function(){
            //     console.log(this);//window调用
            //     console.log(_this);//div#ad
            //     _this.style.background = 'pink';
            // },2000);

            // 2.箭头函数
            setTimeout(()=>{
                console.log(this);//div#ad
                this.style.background = "pink";
            })
        })
    </script>
举报

相关推荐

0 条评论