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.

8
  • 1
    node doesn't support experimental syntax 'classProperties' - yet - it's stage 3 Apr 15, 2019 at 3: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. Apr 15, 2019 at 3:18
  • 2
    the so called duplicate has nothing to do with this syntax Apr 15, 2019 at 3: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, 2019 at 3:18
  • 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 Apr 15, 2019 at 3:19

0

Browse other questions tagged or ask your own question.