Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

unexpected token = for class properties in node 8.4

Tags:

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

gives me the following error:

        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 
like image 599
Elad Katz Avatar asked Nov 27 '17 18:11

Elad Katz


2 Answers

Update
Support for instance class fields starts with node >= 12.


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 = [];     }     // ... } 

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 = []; 
like image 80
JJWesterkamp Avatar answered Oct 15 '22 11:10

JJWesterkamp


Instance class fields will be supported as of Node v12, so one solution is to use a version >= 12 once it is released.

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

For now if you're interested the nightly builds are at: https://nodejs.org/download/nightly/

like image 26
giraffesyo Avatar answered Oct 15 '22 09:10

giraffesyo