节点 8.4 中的 class 属性的意外标记 =

unexpected token = for class properties in node 8.4

运行节点(v8.4)中的以下代码

class TodoStore {
    todos = [];

    get completedTodosCount() {
        return this.todos.filter(
            todo => todo.completed === true
        ).length;
    }

    report() {
        if (this.todos.length === 0)
            return "<none>";
        return `Next todo: "${this.todos[0].task}". ` +
            `Progress: ${this.completedTodosCount}/${this.todos.length}`;
    }

    addTodo(task) {
        this.todos.push({
            task: task,
            completed: false,
            assignee: null
        });
    }
}

const todoStore = new TodoStore();

todoStore.addTodo("read MobX tutorial");
console.log(todoStore.report());

todoStore.addTodo("try MobX");
console.log(todoStore.report());

todoStore.todos[0].completed = true;
console.log(todoStore.report());

todoStore.todos[1].task = "try MobX in own project";
console.log(todoStore.report());

todoStore.todos[0].task = "grok MobX tutorial";
console.log(todoStore.report());

给我以下错误:

        todos = [];
              ^

SyntaxError: Unexpected token =
    at createScript (vm.js:74:10)
    at Object.runInThisContext (vm.js:116:10)
    at Module._compile (module.js:537:28)
    at Object.Module._extensions..js (module.js:584:10)
    at Module.load (module.js:507:32)
    at tryModuleLoad (module.js:470:12)
    at Function.Module._load (module.js:462:3)
    at Function.Module.runMain (module.js:609:10)
    at startup (bootstrap_node.js:158:16)
    at bootstrap_node.js:598:3

更新
支持实例 class 字段以 node >= 12.

开头

根据 this table,任何版本的节点都不支持文字 class 属性。您仍然需要在 class 构造函数中设置任何实例属性:

class TodoStore {

    constructor() {
        this.todos = [];
    }
    // ...
}

如果你想定义一个 static 属性,你可以在声明 class 之后将其直接分配给 TodoStore 引用:

TodoStore.todos = [];

实例 class 字段将在 Node v12 中得到支持,因此一种解决方案是在发布后使​​用 >= 12 的版本。

https://node.green/#ESNEXT-candidate--stage-3--instance-class-fields

现在,如果您有兴趣,夜间构建位于:https://nodejs.org/download/nightly/