我有以下对象。我一直工作到使用setinterval。
我意识到this
成为对象timeout
class test{
constructor(){
this.counter = 0
}
startCounter(){
this.increment()
setInterval(this.increment, 1000)
}
increment(){
this.counter++
console.log(this.counter)
}
}
var t = new test()
t.startCounter()
输出:
1
NaN
NaN
NaN
NaN
NaN
NaN
How to access the correct `this` inside a callback?建议我使用var self = this
,但ES6不支持私有变量
答案 0 :(得分:-1)
请尝试以下操作:
class test{
constructor(){
this.counter = 0
}
startCounter(){
this.increment()
setInterval(this.increment.bind(this), 1000)
}
increment(){
this.counter++
console.log(this.counter)
}
}
var t = new test()
t.startCounter()