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

문제

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.

도움이 되었습니까?

해결책

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

다른 팁

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);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top