Description
A static constructor is a function that is run only once when the class is loaded. It can be used to initialize static class members and maybe as entry point to the application.
Suggested syntax is:
class MyClass {
static initialized = false;
static constructor() {
MyClass.initialized = true;
}
}
alert(MyClass.initialized);
That would be same as the following:
class MyClass {
static initialized = false;
static __ctor = (() => {
MyClass.initialized = true;
})();
}
alert(MyClass.initialized);
Except that __ctor
does not need to be assigned to the class in the output code, and only needs to be invoked in an anonymous function. Also compiler can check that no more than one static constructor is defined in a class.
Update: Since this generates an Immediately-Invoked Function Expression (IIFE), compiler should make sure to move it to the end of the class definition in the output JavaScript.
TypeScript:
class MyClass {
static constructor() {
MyClass.initialized = true;
}
static initialized = false;
}
Expected JavaScript output:
var MyClass = (function () {
function MyClass() {
}
MyClass.initialized = false;
// run last
(function () {
MyClass.initialized = true;
})();
return MyClass;
})();
Note that body of the static constructor is moved to the bottom and invoked.
Related suggestion in codeplex: Please add static constructors to classes