Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Object - 'Static Initialization'

Tags:

javascript

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

like image 877
Jason Avatar asked Jun 30 '10 19:06

Jason


1 Answers

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();
like image 120
Peter Bailey Avatar answered Nov 12 '22 05:11

Peter Bailey