簡體   English   中英

從另一個擴展類調用函數

[英]Calling a function from another extended class

我有我的主要階段,並且我有兩個對象(塊),這兩個對象都從“ Block”類擴展。 “塊”類不是從主類擴展的。

我希望從Main Stage類中調用“塊”類或其子類中的函數。 函數將根據您調用函數的對象的不同而做些不同的事情(在數組中添加了不同的東西,以及不同數量的東西)。 實現此目的的最佳方法是什么?

抱歉,我現在沒有代碼要顯示,我只是想坐下來現在就做,但感到很迷茫。

不太確定我會遵循,所以我將假設您是這個意思。

您有一個名為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
}

希望這就是你所追求的

一般的想法是在父類中定義函數,然后重寫子類中的函數以執行不同的操作。 然后,您可以在各個子類上調用該函數,根據該塊,它將執行不同的操作。

一個簡單的例子:

方塊類:

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"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM