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

StackOverflow https://stackoverflow.com/questions/14888148

Pergunta

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.

Foi útil?

Solução

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();

Outras dicas

This is how you can access the dynamic class (Scene) & it's properties / methods :

var myDynamicClasses:Array = [Scene];   // Required

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

This could throw an error, if the first line is not included. Because, when the compiler notices the class Scene (not the one from adobe's package) is not being used it ignores it. Thus it would be not available for dynamic initialization.

We could force the compiler to include these classes by putting these class names in variables or declare an array as above as a quick hack.

If you have many dynamic classes, you could add a reference to them in this array & each class will be included by the compiler for dynamic initialization.

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

Should throw an error because the compiler can no longer assume that i is a scene when it gets to line 2. If you were to coerce the Class object, it should work.

var i:Class = Scene;
trace((Scene(Class).title);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top