How can I create static variables in Javascript?
You can define static functions in JavaScript using the static keyword:
class MyClass {
static myStaticFunction() {
return 42;
}
}
MyClass.myStaticFunction(); // 42
As of this writing, you still can't define static properties (other than functions) within the class. Static properties are still a Stage 3 proposal, which means they aren't part of JavaScript yet. However, there's nothing stopping you from simply assigning to a class like you would to any other object:
class MyClass {}
MyClass.myStaticProperty = 42;
MyClass.myStaticProperty; // 42
Final note: be careful about using static objects with inheritance - all inherited classes share the same copy of the object.