javascript ES6 类:脚本中出现意外标记?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33042084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 16:03:32  来源:igfitidea点击:

ES6 Classes: Unexpected token in script?

javascriptecmascript-6

提问by panthro

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

我正在复制一个尝试学习 ES6 的示例,但出现编译错误:

Unexpected token (2:5)

It appears to be referring to the count = 0;

它似乎指的是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);
    }
}

回答by nils

In ES2015, when using the classsyntax, 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)

在 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();

Check out the fiddle:

看看小提琴:

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

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

回答by imprfekt

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

可能是编译器的问题。检查您使用的 Babel 版本。
就我而言,我错过了babel-preset-stage-0依赖项。

回答by Riley Green

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

晚了 3 年,所以你可能想通了,但我将 count 变量放在构造函数中

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

通过调用tick函数给它更多的控制

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()