意外令牌=节点8.4中的类属性 [英] unexpected token = for class properties in node 8.4

查看:100
本文介绍了意外令牌=节点8.4中的类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

running the following code in node (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


推荐答案

更新

对实例类字段的支持始于节点> = 12

任何版本的节点都不支持文学类属性,根据< a href = https://node.green/#ESNEXT-candidate--stage-3--instance-class-fields rel = noreferrer>此表。您仍然必须在类构造函数中设置任何实例属性:

Literal class properties are not supported by any version of node, according to this table. You'll still have to set any instance properties inside your class constructor:

class TodoStore {

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

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

If you wish to define a static property, you'd assign that directly to the TodoStore reference, after the class has been declared:

TodoStore.todos = [];

这篇关于意外令牌=节点8.4中的类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆