从另一个函数访问类实例 - getDefinitionByName(AS3)

时间:2014-11-22 21:22:37

标签: actionscript-3

我有一个函数sceneLoader,它将使用getDefinitionByName从字符串中实例化Class Scene1的对象。然后我想从另一个函数访问Scene1中的函数(sceneHandler)。

public class Main extends MovieClip{

    private var sceneNumber:int = 1;
    private var SceneRef:Class;
    private var sceneString:String;

    public function Main(){
        sceneLoader();
        responseHandler();
    }

    private function sceneLoader():void{
        sceneString = "Scene" + int(sceneNumber);
        SceneRef = getDefinitionByName(sceneString) as Class;
        var scene = new SceneRef();
        addChild(scene);
    }
    private function responseHandler():void{
        scene.sceneHandler(); //Obviously this will not work
    }
}

类Scene1

public class Scene1 extends MovieClip{
    public function sceneHandler():void{
        //Do something
    }
}

问题是场景超出了范围。我无法在函数外部实例化Scene1,因为我需要先调用getDefinitionByName。我还想保留稍后加载场景的功能。 如何从responseHandler调用sceneHandler?

编辑:我已经尝试了

public class Main extends MovieClip{

    private var sceneNumber:int = 1;
    private var SceneRef:Class;
    private var sceneString:String;

    public function Main(){
        sceneLoader();
        responseHandler();
    }

    private function sceneLoader():void{
        addChild(getScene());//Does not work
    }

    private function responseHandler():void{
        getScene().sceneHandler(); //Works now
    }

    private function getScene():Object{
        sceneString = "Scene" + int(sceneNumber);
        SceneRef = getDefinitionByName(sceneString) as Class;
        var scene = new SceneRef();
        //addChild(getScene());//This does work but doesn't suit my need
        return scene;
     }
}

现在我无法将对象添加到舞台上。 我收到错误:

  

使用静态类型Object将值隐式强制转换为可能不相关的类型flash.display:DisplayObject。

1 个答案:

答案 0 :(得分:0)

我明白了。我只是忘了扮演一个DisplayObject。

public class Main extends MovieClip{

    private var sceneNumber:int = 1;
    private var SceneRef:Class;
    private var sceneString:String;

    public function Main(){
        sceneLoader();
        responseHandler();
    }

    private function sceneLoader():void{
        addChild(getScene() as DisplayObject);
    }

    private function responseHandler():void{
        getScene().sceneHandler();
    }

    private function getScene():Object{
        sceneString = "Scene" + int(sceneNumber);
        SceneRef = getDefinitionByName(sceneString) as Class;
        var scene = new SceneRef();
        return scene;
     }
}

显然:

import flash.display.DisplayObject;