this关键字指向问题

1.对象方法里的this,指向调用方法的对象
2.事件中的this指向触发事件的DOM对象
3.构造函数中的this指向new创建的对象(new关键字做了什么?)
new会创建一个对象,并将构造函数中的this指向创建中的对象
4.箭头函数中没有this(箭头函数外指向谁,箭头函数里的this指向谁)

function Fn(){
            this.name='miaomiao'
            this.sayHi=function(){
                // this指向fn
                console.log(this);
                setTimeout(()=>{
                    //this指向fn
                    console.log(this);
                }
                ,1000)
            }
        }
        let fn=new Fn()
        fn.sayHi()

5.计时器中的this指向window(计时器函数为全局函数,全局函数中的this指向window)

 function Fn(){
            this.name='miaomiao'
            this.sayHi=function(){
                // this指向fn
                console.log(this);
                setTimeout(function(){
                    //this指向window
                    console.log(this);
                },1000)
            }
        }
        let fn=new Fn()
        fn.sayHi()

image

posted @   Kira的学习笔记  阅读(31)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示