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
I need something that runs only once when the class is loaded.
You shouldn't be using classes if you just use them as a bag of methods. Use an object instead. However, it's still possible to run such code. Just put it before or after the class definition.
console.log('before class is created')
class Foo {}
console.log('after class was created');
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()
Inside the "static constructor" you can add properties to the class object with MyClass.prop = value
, or if you're keen to refer to MyClass
as this
, change the function expression to an arrow function expression.
You can make _staticConstructorDummyResult
non-enumerable using Object.defineProperty(), or if you don't mind requiring Chrome (it won't work in Firefox currently), you can add a #
at the front of the name to make it a private property.
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';
}