0

I'd like to know if Javascript's class syntax support static, or class variables in the following way

class MyClass {
  var myVar = 0;

  //I have also tried these combinations of keywords
  static var myVar = 0;
  static myVar = 0;
  this.myVar = 0;
  this.var myVar = 0;
}

MyClass.myVar //0

I see that this is possible using the this keyword when defining a class with the function keyword, but I don't see if it's possible using class. I would hope it is, considering the class syntax supports static functions. I have tried the following.

I do not wish to use the constructor method, because then the variable would be an instance variable, and that's not what I'm asking for.

Csteele5
  • 1,262
  • 1
  • 18
  • 36
  • It doesn't support it yet, there is a proposal, perhaps in ES2017... You can use Babel though. – elclanrs Dec 28 '16 at 18:43
  • Why don't you set it on the `MyClass` itself then? `MyClass.myVar = 0` – thefourtheye Dec 28 '16 at 18:43
  • Perhaps [this question](http://stackoverflow.com/questions/1535631/static-variables-in-javascript) will help. Also, @thefourtheye is correct: you can write `MyClass.myVar = 0;` which works just fine. – chazsolo Dec 28 '16 at 18:46
  • You can do this in TypeScript if that's your cup of tea. –  Dec 28 '16 at 18:47
  • @chazsolo It does not "works just fine" when considering inheritance. –  Dec 28 '16 at 18:48
  • @torazaburo by all means please, enlighten me - perhaps I've been doing something all along, the consequences of which I'm not aware. – chazsolo Dec 28 '16 at 19:05
  • @thefourtheye with this solution, am I able to allow the static functions of MyClass to manipulate that variable? After some experimentation, it does not appear to be the case. – Csteele5 Dec 28 '16 at 19:38
  • @Csteele5 Please note that it has the limitation mentioned by @torazaburo above. Also, you need to access the variable with the function name, `MyClass.myVar`. I assume you were trying to manipulate them with `this` – thefourtheye Dec 28 '16 at 19:42

0 Answers0