0

I am studying the core javascript, and met the following code (https://javascript.info/private-protected-properties-methods#protecting-wateramount)

class CoffeeMachine {
  waterAmount = 0; // the amount of water inside

  constructor(power) {
    this.power = power;
    alert(`Created a coffee-machine, power: ${power}`);
  }

}

// create the coffee machine
let coffeeMachine = new CoffeeMachine(100);

// add water
coffeeMachine.waterAmount = 200;

Line 2, waterAmount = 0 run in browser environment, but not in node environment, saying

  waterAmount = 0;
              ^

SyntaxError: Unexpected token =
    at new Script (vm.js:80:7)
    at createScript (vm.js:274:10)

How come? So line 2 is not a good practice, I assume? Thanks for shedding light.

Ele
  • 33,468
  • 7
  • 37
  • 75
Jimmy Chu
  • 972
  • 8
  • 27
  • 1
    node doesn't support `experimental syntax 'classProperties'` - yet - it's stage 3 – Jaromanda X Apr 15 '19 at 03:17
  • 1
    That's class field syntax, which requires a transpiler for some environments. I think it's perfectly fine to use, as long as you transpile before use, if needed - which it appears that you do need to. Either transpile, or use the older method, of `this.waterAmount = 0` inside the constructor. – CertainPerformance Apr 15 '19 at 03:18
  • 2
    the so called duplicate has nothing to do with this syntax – Jaromanda X Apr 15 '19 at 03:18
  • 1
    @JaromandaX It can be enabled with a flag. I highly suspect it'll be released unflagged soon, though, as node uses V8 (and public fields recently landed in Chrome). – jhpratt Apr 15 '19 at 03:18
  • 1
    @JaromandaX The second answer on the linked question describes exactly how class field syntax can be rewritten without class fields. – CertainPerformance Apr 15 '19 at 03:19
  • 2
    yes, I said `yet` because if someone doesn't even know what the problem is, using experimental features is probably the last thing you want to recommend :p – Jaromanda X Apr 15 '19 at 03:19
  • 1
    @CertainPerformance This question doesn't seem to be about static fields, though. – jhpratt Apr 15 '19 at 03:20
  • 1
    @CertainPerformance - oh, right - so someone posted an answer there that doesn't even cover the question there - and you think this user would know what to look for :p – Jaromanda X Apr 15 '19 at 03:20

0 Answers0