Search code examples
classvariablesreflectionactionscripthint

is it possible to put Class in a variable and access the class's static variables and functions in actionscript3?


Say I had the following class

public class Scene{ 
  public static var title="new scene";
  public function Scene(){}
  public static function start() { trace("scene started"); }
}

How can you access the Scene class's static variables and functions like this?

var i:Class = Scene;
trace(i.title);
i.start();

I'm trying to figure out how variables assigned with Class work in actionscript. Any tips would be welcome. Thanks.


Solution

  • Static methods are called from the class:

    trace(Scene.title);
    Scene.start();
    

    Singleton patterns enable constructor, local reference, and potentially abstraction through interface classes.

    Example of Scene as a singleton:

    package
    {
    
        public class Scene
        {
    
            private static var instance:Scene = new Scene();
    
            public static function getInstance():Scene
            {
                return instance;
            }
    
            public var title:String = "new scene";
    
            public function Scene()
            {
                if (instance)
                    throw new Error("Scene is a singleton and can only be accessed through Scene.getInstance()");
            }
    
            public function start():void
            {
                trace("scene started.");
            }
    
        }
    }
    

    Your example implementation would now be:

    var i:Scene = Scene.getInstance();
    trace(i.title);
    i.start();