22

I'm copying an example trying to learn ES6 but i'm getting a compile error:

Unexpected token (2:5)

It appears to be referring to the count = 0;

What am I doing wrong?

class Counter {
    count = 0;

    constructor() {
        setInterval(function() {
            this.tick();
        }.bind(this), 1000);
    }

    tick() {
        this.count ++;
        console.log(this.count);
    }
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
panthro
  • 22,779
  • 66
  • 183
  • 324

3 Answers3

27

In ES2015, when using the class syntax, you need to define instance variables either in the constructor or one of the methods (there is a proposal for the next iteration, ES2016, to allow for your syntax: ES Class Fields & Static Properties)

class Counter {

    constructor() {
        this.count = 0;
        setInterval(function() {
            this.tick();
        }.bind(this), 1000);
    }

    tick() {
        this.count++;
        console.log(this.count);
    }
}

var c = new Counter();

Check out the fiddle:

http://www.es6fiddle.net/ifjtvu5f/

nils
  • 25,734
  • 5
  • 70
  • 79
2

3 years late so you probably figured it out, but I placed the count variable in the constructor

class Counter {
    constructor(count = 0) {
      this.count = count
        setInterval(function() {
            this.tick();
        }.bind(this), 1000);
    }

    tick() {
        this.count ++;
        console.log(this.count);
    }
}

let counter = new Counter;
counter.tick()

gave it more control by calling the tick function

class Counter {
    constructor(count = 0) {
      this.count = count;
    }

    tick() {
        let count = this.count;
        setInterval(function() {
         console.log(count++);
        }, 1000);
    }
}
let counter = new Counter;

// counter.tick()
  • Seems identical to the [existing answer](https://stackoverflow.com/a/33042437/6243352) so I'm not sure what value this adds. `let counter = new Counter;` seems incorrect. You probably want to call the constructor. – ggorlen Jun 04 '22 at 03:28
1

Perhaps it's the compiler issue. Check what version of Babel you're using.
In my case I missed the babel-preset-stage-0 dependency.

imprfekt
  • 317
  • 4
  • 9