Static variables in JavaScript

后端 未结 30 2877
别那么骄傲
别那么骄傲 2020-11-22 01:55

How can I create static variables in Javascript?

30条回答
  •  忘掉有多难
    2020-11-22 02:33

    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.

提交回复
热议问题