我正在复制一个尝试学习 ES6 的示例,但出现编译错误:
Unexpected token (2:5)
好像是指count=0;
我做错了什么?
class Counter {
count = 0;
constructor() {
setInterval(function() {
this.tick();
}.bind(this), 1000);
}
tick() {
this.count ++;
console.log(this.count);
}
}
最佳答案
在 ES2015 中,当使用 class
语法时,您需要在构造函数或其中一个方法中定义实例变量(下一个迭代,ES2016,允许您语法: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();
查看 fiddle :
关于javascript - ES6 类 : Unexpected token in script?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33042084/