AS3 - 动态初始化对象

时间:2016-11-11 13:31:00

标签: actionscript-3 flash

我一直在努力改进我经常使用的代码,并且想知道是否有一种简单的方法可以实现这一点。

我有一个导航类,用于定义构造函数之前的对象(private var exampleScreen:ExampleScreen;)。

基于ChangeScreenTo函数的字符串依赖注入(destinationScreen:String),是否可以抓取定义的屏幕并对其进行初始化(exampleScreen = new ExampleScreen();)? 无论哪种方式,有没有人比我或我目前的switch语句解决方案有更好的建议?

示例代码:

package{
    public class ScreenController extends MovieClip {
        private var currentScreen: DisplayObject;
        //SCREENS
        private var exampleScreen1:ExampleScreen1;
        private var exampleScreen2:ExampleScreen2;
        ...
        public function ScreenController() {
            ...
        }
        public function ChangeScreenTo(desinationScreenName: String) {
            //REMOVE CURRENT SCREEN
            if (currentScreen != null) {
                removeChild(currentScreen);
                currentScreen = null;
            }
            switch (destinationScreenName) {
                case "exampleScreen1":
                    exampleScreen1 = new ExampleScreen1();
                    break;
                case "exampleScreen2":
                    exampleScreen2 = new ExampleScreen2();
                    break;
                ...
            }
            mcDestinationScreen = this[(destinationScreenName)];
            addChild(mcDestinationScreen);
            currentScreen = mcDestinationScreen;
        }
    }
}

1 个答案:

答案 0 :(得分:0)

可能这样更好:

    public function ChangeScreenTo(desinationScreenName: String) {
        //REMOVE CURRENT SCREEN
        if (currentScreen != null) {
            removeChild(currentScreen);
            currentScreen = null;
        }
        switch (destinationScreenName) {
            case "exampleScreen1":
                currentScreen = exampleScreen1 = new ExampleScreen1();
                break;
            case "exampleScreen2":
                currentScreen = exampleScreen2 = new ExampleScreen2();
                break;
            ...
        }
        addChild(currentScreen);
    }