tags:

views:

47

answers:

2

Hi,

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

+3  A: 

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();
Peter Bailey
Thanks, perfect.
Jason
+1  A: 
// Object Contructor
function MyObject(name) {

  if (!this.done) {
    this.done = true;
    // init stuff
    // ...
  }

  this.name = name;
  return this; // optional
}

// available in all instances
MyObject.prototype.done = false;
galambalazs