I’m converting some Java code to Javascript, and the Java object has a Static Initialization block that populates two arrays in the object. My understanding is that this initializer runs only once no matter how many objects are created. Can I do such a thing in Javascript?
Java code:
public final class MyObject {
private MyObject() { }
// ...
static {
// Run once static init code here
}
}
Can this run-once style initialization be done in Javascript?
Thanks
Not really.
The whole concept of “static” members doesn’t really apply to javascript. You can achieve them but only in a “public” way.
This sort of does what you’re asking for, but it’s really just a bunch of kludgy syntax over “run this function once as triggered by a constructor”.