为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
温温酱 2019-03-18 04:29:19
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)这语句,请问如何使着代码正常运行? 求大神解答,很是疑惑
查看完整描述

2 回答

?
烙印99

TA贡献1829条经验 获得超13个赞

你的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) 就可以了

查看完整回答
反对 回复 2019-03-18
?
守着一只汪

TA贡献1872条经验 获得超3个赞

bind对象进去就行了
setInterval(test.all.bind(test),1000);

查看完整回答
反对 回复 2019-03-18
  • 2 回答
  • 0 关注
  • 511 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信