0

I've seen member variables in ES6 declared like this

export class MyClass
{
   x = null;

   constructor()  {
      this.x = 1;
   }

   write() {
      console.log(this.x);
   }
}

and babel seem to transpile it fine.

Is this a valid way to declare member variables?

Don Box
  • 3,166
  • 3
  • 26
  • 55
  • 1
    There is no such thing as "member variables" in JS. And what you have seen is not ES6, but an experimental feature proposal for ES8. Don't use it. – Bergi Mar 21 '16 at 20:06

2 Answers2

2

I do not believe this is correct. At least, the MDN does not mention any such syntax.

As for your example, let's work through it line by line.

class MyClass { // Class declaration, all good here
   x = null; // I assume you're telling javascript that the variable x exists?

   constructor()  {
      this.x = 1; // You do that here just fine.
   }

   write() {
      console.log(this.x); // And here we use the variable, after the constructor ran
   }
}

I don't see any value in declaring the member variables seperately. You create it in the constructor. That should be all you need

JoshWillik
  • 2,624
  • 21
  • 38
2

This is part of the suggestion for ES Class Fields & Static Properties. It's supported by babeljs, with this plugin. It's a babel stage-1 plugin, so if you're using stage-1 or stage-0, this is supported.

Ori Drori
  • 183,571
  • 29
  • 224
  • 209