0

I have the following object. I works until I use setinterval . I realise that this becomes the object 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()

Outputs:

1
NaN
NaN
NaN
NaN
NaN
NaN

How to access the correct `this` inside a callback? suggest that I should use var self = this but ES6 does not support private variables

TSR
  • 17,242
  • 27
  • 93
  • 197
  • @T.J Crowder This link has no ES6 objects. I do not see is this a duplicate – TSR Sep 07 '18 at 14:38
  • 1
    The issue has nothing to do with "ES6 objects." It has to do with `this`. If you take the time to read the answers, you'll understand. – T.J. Crowder Sep 07 '18 at 14:39
  • Maybe the solution is the same but the scenario is different @T.J. Crowder – Jose Mato Sep 07 '18 at 14:40
  • It says I should use var self = this but ES6 does not support private variables – TSR Sep 07 '18 at 14:40
  • 1
    @JoseMato - Again, doesn't matter. – T.J. Crowder Sep 07 '18 at 14:40
  • @TSR You haven't read all of the accepted answer on the linked question. It gives several solutions for several scenarios. The solutions under the headings "Explicitly set `this` of the callback - part 1" and "ECMAScript 6: Use arrow functions" would both solve your problem neatly. – Jordan Running Sep 07 '18 at 14:42
  • 3
    @TSR - The answers there say a lot more than that. Take the time to actually read through the answers and digest what they're saying, rather than focussing on the idea that this isn't covered there and giving up after 30 seconds. This is **well-covered** in the answers there, such as [this one](https://stackoverflow.com/a/20279485/157247). – T.J. Crowder Sep 07 '18 at 14:42

1 Answers1

1

Please try this:

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()
enxaneta
  • 31,608
  • 5
  • 29
  • 42