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就是正確的對(duì)象,可正常調(diào)用到func1,func2,func3
setInterval(test.all,1000)//這打印出的this是window,理所當(dāng)然調(diào)不到函數(shù)
請(qǐng)問在setInterval(test.all,1000)語句中,為什么this突然指向了window?
我現(xiàn)在寫的代碼需要setInterval(test.all,1000)這語句,請(qǐng)問如何使著代碼正常運(yùn)行?
求大神解答,很是疑惑
2 回答

烙印99
TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超13個(gè)贊
你的setInterval(test.all,1000)
相當(dāng)于
setInterval(function(){
console.log(this)
this.func1()
this.func2()
this.func3()
},1000)
這里已經(jīng)脫離test
的上下文了,所以this
指向window
要想正常執(zhí)行的話,就要把test
上下文傳進(jìn)去:這樣setInterval(test.all.apply(test),1000)
就可以了

守著一只汪
TA貢獻(xiàn)1872條經(jīng)驗(yàn) 獲得超4個(gè)贊
bind對(duì)象進(jìn)去就行了setInterval(test.all.bind(test),1000);
- 2 回答
- 0 關(guān)注
- 549 瀏覽
添加回答
舉報(bào)
0/150
提交
取消