js中setInterval函数使用时出现的问题

function Test(){
    this.func1=function(){
        console.log("func1")
    }
    this.func2=function(){
        console.log("func2")
    }
    this.func3=function(){
        console.log("func3")
    }
    this.all=function(){
        console.log(this)
        this.func1()
        this.func2()
        this.func3()
    }
}
var test=new Test()
test.all()//这打印出的this就是正确的对象,可正常调用到func1,func2,func3
setInterval(test.all,1000)//这打印出的this是window,理所当然调不到函数

请问在setInterval(test.all,1000)语句中,为什么this突然指向了window?

我现在写的代码需要setInterval(test.all,1000)这语句,请问如何使着代码正常运行?

求大神解答,很是疑惑

温温酱
浏览 512回答 2
2回答

烙印99

你的setInterval(test.all,1000) 相当于 setInterval(function(){ console.log(this) this.func1() this.func2() this.func3() },1000) 这里已经脱离test的上下文了,所以this指向window 要想正常执行的话,就要把test上下文传进去:这样setInterval(test.all.apply(test),1000) 就可以了

守着一只汪

bind对象进去就行了setInterval(test.all.bind(test),1000);
打开App,查看更多内容
随时随地看视频慕课网APP