Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
653 views
in Technique[技术] by (71.8m points)

ecmascript 6 - Static Constructor in Javascript ES6

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 there any way to implement something like this ?

class Commander{

    static onData(){
         console.log("blabla");
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It does seem neater to have class-setup code inside the class body so the "class expression" is self-contained. ES6 accepts the syntax static constructor() {/* do stuff */} in a class body but never runs it. Perhaps it is for future language expansion? Anyway, here is one way to achieve the desired result. The trick is to initialize a static property with an immediately-executed function expression that does your class setup:

class MyClass {
  static _staticConstructorDummyResult = (function() {
    console.log('static constructor called') // once!
  })()
  constructor () {
    console.log('instance constructor called')
  }
}
let obj = new MyClass(),
    obj2 = new MyClass()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...