2012-03-29 23 views
0

我有我的主要階段,並且我有兩個對象(塊),這兩個對象都從「塊」類擴展。 「Block」類不從主類擴展。從另一個擴展類調用函數

我想要在Main Stage Class中的「Block」類或它的子類中調用一個函數。這些函數會根據您調用函數的哪個對象(添加不同的東西,以及對數組的不同數量)做稍微不同的事情。什麼是實施這個最好的方法?

對不起,我現在沒有代碼顯示,我只是試圖坐下來,現在就做,但感覺很失落。

+0

你的意思是這兩個塊應該具有相同的功能,即使它們擴展了相同的功能,這些功能應根據哪個塊調用它來做兩件不同的事情? – Marty 2012-03-29 00:14:00

回答

0

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

您有一個名爲

類創建兩個的這些區塊的並存儲它們,可能是從你的基類的數組。

//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 
} 

希望這是你追求的

+0

省長。謝謝你們倆。 – 2012-03-29 01:19:32

0

的總體思路是,以確定父類中的函數然後重寫子類中的函數來完成不同的事情。然後,你可以在不同的子類上調用該函數,並根據該塊執行不同的操作。

一個簡單的例子:

Block類:

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" 
+0

省長。謝謝你們倆。 – 2012-03-29 01:19:56