22

在节点(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
4

2 回答 2

33

对实例类字段的更新
支持从node >= 12开始。


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

class TodoStore {

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

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

TodoStore.todos = [];
于 2017-11-27T18:07:39.487 回答
3

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

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

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

于 2019-03-22T11:04:00.137 回答