Static Constructor in Javascript ES6

后端 未结 3 1522
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-20 13:36

In ES6, I can create static methods like below. But I need to define a static constructor but no success. I need something that runs only once when the class is loaded. I Is

3条回答
  •  粉色の甜心
    2020-12-20 14:31

    If you insist on a static constructor: Define a static method and invoke it after the class definition.

    class Foo {
      static staticConstructor() {
        console.log('Foo has been constructed statically!');
      }
    }
    
    Foo.staticConstructor()
    

    Of course this is not really necessary. Except mabye to clearly express the notion of a static constructor. However this smells like Java.

    Felix proposed a fine solution by putting code before or after the class definition.

    For example: Do you want to pre-calculate some static members? Just assign the calculation result after the class definition!

    class Foo {}
    
    Foo.preCalculated = calculate();
    
    function calculate() {
      console.log('Do some hard work here');
      return 'PRECALCULATED';
    }
    

提交回复
热议问题