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 @ 2022-04-06 11:31  Kira的学习笔记  阅读(40)  评论(0)    收藏  举报