问题:在setInterval和setTimeout中传入函数时,函数中的this会指向window对象

1.利用闭包

let box = document.getElementById('box')
box.addEventListener('click', function(){
    let that  = this
    setTimeout(function(){
        console.log(that)
    }, 1000)
})

let box = document.getElementById('box')
    let obj = {
        name: 'lee',
        age: 18,
        fn: function(){
            console.log(this)
        }
    }
    box.addEventListener('click', function(){
        setTimeout(obj.fn, 1000)     //window
    })

    box.addEventListener('click', function(){
        setTimeout(function(){    //obj
            obj.fn()      
        }, 1000)
    })

2.箭头函数

let box = document.getElementById('box')
box.addEventListener('click', function(){
    setTimeout(()=>{
        console.log(this)
    }, 1000)
})

 

 3.bind()函数

let box = document.getElementById('box')
box.addEventListener('click', function(){
    setTimeout(function(){
        console.log(this)
    }.bind(this), 1000)
})

posted on 2021-05-10 15:46  李起桉  阅读(118)  评论(0编辑  收藏  举报