ES6对象中的setInterval

时间:2018-09-07 14:34:56

标签: javascript node.js object methods setinterval

我有以下对象。我一直工作到使用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不支持私有变量

1 个答案:

答案 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()