【问题标题】:Calling a function from another extended class从另一个扩展类调用函数
【发布时间】:2012-03-29 00:12:00
【问题描述】:

我有我的主舞台,我有两个对象(块),这两个对象都是从“块”类扩展而来的。 “块”类不是从主类扩展而来的。

我想在主舞台类中调用“块”类或其子类中的函数。根据您调用函数的对象,这些函数会做稍微不同的事情(向数组添加不同的东西和不同数量的东西)。实现这一点的最佳方法是什么?

很抱歉,我现在没有可显示的代码,我只是想坐下来做,但感觉很失落。

【问题讨论】:

  • 你的意思是这两个块应该具有相同的功能,即使它们扩展了相同的东西,这些功能应该根据哪个块调用它来做两种不同的事情?

标签: actionscript-3


【解决方案1】:

不太确定我是否遵循,所以我假设你是这个意思。

你有一个名为Block的类

您创建其中两个 Block 并将它们存储在您的基类中的数组中。

//stage base class
var blockArray:Array = new Array()

private function createBlocks():void{

    var blockOne:Block = new Block(1); //passing in an int to block, could be anything but this 
                                       // will be used to do slightly different things

    var blockTwo:Block = new Block(2);
    blockArray.push(blockOne...blockTwo)
}

现在在你的块类中

//block class
class Block{
   var somethingDifferent:int; //this is where we will store the int you pass in when the blocks are made
   public function Block(aInt:int){
       somethingDifferent = aInt //grabbing the int
   }

   public function doSomething():void{
       trace(somethingDifferent); //will trace out the number passed
   }

}

现在回到你的主课

//stage base class
private function doSomethingToBlocks():void{
    //lets call doSomething on each block
    Block(blockArray[0]).doSomething() //this will trace 1 because we passed that into the block in our array slot 0
    Block(blockArray[1]).doSomething() //this will trace 2
}

希望这就是你所追求的

【讨论】:

    【解决方案2】:

    总的思路是在父类中定义函数,然后在子类中重写函数来做不同的事情。然后,您可以在各个子类上调用该函数,它会根据块执行不同的操作。

    一个简单的例子:

    方块类:

    public function getBlockType():String
    {
       return "I am a plain block";
    }
    

    第一个块子类

    public override function getBlockType():String
    {
       return "I am a cool block";
    }
    

    第二块子类:

    public override function getBlockType():String
    {
       return "I am an even cooler block";
    }
    

    阶段:

    //add the first block
    var coolBlock:CoolBlock = new CoolBlock();
    addChild(coolBlock);
    
    //add the second block
    var coolerBlock:EvenCoolerBlock = new EvenCoolerBlock();
    addChild(coolerBlock);
    
    //call the functions
    trace(coolBlock.getBlockType());//outputs "I am a cool block"
    trace(coolerBlock.getBlockType());//outputs "I am an even cooler block"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-07-18
      • 1970-01-01
      • 1970-01-01
      • 2012-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多