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".
function MyObject()
{
if ( 'undefined' == typeof MyObject.__initialized )
{
// static stuff
alert( 'hi' );
MyObject.__initialized = true;
}
// Proceed with constructing instance of MyObject
}
new MyObject();
new MyObject();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With