I am learning about static
methods and fields to use in my app.
I have written the following codes to test what I have learned:
class ClassWithStatic {
static childclass = new SubClass("Hello");
static writeIn() {
console.log("Hello world!");
}
}
class SubClass {
constructor(text) {
console.log(text);
}
}
ClassWithStatic.writeIn();
However, this code returned an error; Uncaught ReferenceError: Cannot access 'SubClass' before initialization
. When I searched this keyword in a browser, I found out that the error had occurred because Hoisting is not working.
How can I solve this problem without changing the order of the classes?
Well, actually, classes are hoisted, but its values are not automatically initialized (class must be defined before it can be constructed).
That's basically the main difference between classes and functions, as functions will be hoisted and initialized (so you call them before they are defined code-wise), but classes must be defined prior to constructing them. So I'm afraid you'll have to push the Class declaration above.
Check for more info here.