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);
}
}
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.
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.
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.
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With