Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ES6 Classes: Unexpected token in script?

Tags:

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);
    }
}
like image 996
panthro Avatar asked Oct 09 '15 15:10

panthro


People also ask

How do I fix an unexpected token?

This error can occur for a number of reasons, but is typically caused by a typo or incorrect code. Luckily, the SyntaxError: Unexpected token error is relatively easy to fix. In most cases, the error can be resolved by checking the code for accuracy and correcting any mistakes.

What is an unexpected token in JavaScript?

Like other programming languages, JavaScript has define some proper programming rules. Not follow them throws an error.An unexpected token occurs if JavaScript code has a missing or extra character { like, ) + – var if-else var etc}. Unexpected token is similar to syntax error but more specific.

What is a very common reason for seeing the error message uncaught Syntax error unexpected token Y '?

The 'Uncaught SyntaxError: Unexpected token u in JSON at position 0' error is caused when the client has been asked to execute JSON. parse() on a string beginning with u instead of the stringified object it was expecting. Usually this is a stringified version of the undefined primitive.

What does uncaught SyntaxError unexpected token '<' mean?

The error Uncaught SyntaxError: Unexpected token < is most commonly caused by your site's code referring to an asset that is no longer available. Most commonly, this is due to a filename change in assets generated during your build.


1 Answers

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/

like image 158
nils Avatar answered Sep 30 '22 05:09

nils