Ok. I'll use that pattern.

I guess we should think about adding getters and setters to our JS. All the runtimes actually support them, we just have to make the appropriate translation. Then you would be able to say:

  function get instance () { return singleton; }

But, if you can initialize a static var to an instance of the class, can you just say:

  public static const instance = new SingletonClass;

? Then you would not need a getter or an accessor to protect the instance...

I think our JS1 translator will choke because it will try to evaluate the constructor before it is defined. (The translator would have to be amended to move static initializers to the class body.)

On 2008-03-22, at 18:09 EDT, Donald Anderson wrote:
Not approved.

1) Tried this in SWF9 doing some hand coding, and can't get around this compile error:

/private/tmp/lzswf9/lzgen64824/SingletonClass.as(6): col: 37 Error: Return value must be undefined.

   return SingletonClass.singleton;
                                   ^

So it does appear that 'new' is behaving like C++ or Java - the object is created, and the value of the reference is determined before the constructor is called.
Maybe use a pattern like this:

 class SingletonClass {
   private static var singleton:SingletonClass = new SingletonClass();
public static function instance():SingletonClass { return singleton; } function SingletonClass() { if (singleton != null) throw "Use SingletonClass.instance() instead of new"}
 }

usage: var s = SingletonClass.instance();

I added the throw because constructors cannot be marked private (at
least flex gives an error).

Reply via email to