你有幾個問題。 首先:要調用靜態方法,您必須參考該類。
Bus.addBus();
這使得閃存知道你指的是總線類的靜態方法,而不是所謂的「addBus()」方法的主類。
其次,在你的Bus.addBus()方法中,你引用了非靜態變量。這可能會導致問題。尤其是,您引用了舞臺對象,因爲沒有靜態舞臺,舞臺對象將爲空。相反,您需要傳遞對舞臺的引用,或者您可以從該函數返回一個新的總線,並讓調用類以適當的方式將它添加到顯示列表中。
我會推薦第二種方法。
另外,您可能會對addBus()靜態方法有進一步的計劃。但我想指出,您可以通過如下構造函數輕鬆完成該功能:
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.display.Stage;
public class Bus extends Sprite
{
public function Bus(stageReference:Stage)
{
this.x = stageReference.stageWidth/2;
this.y = stageReference.stageHeight/2;
stageReference.addChild(bus); // This is kind of bad form. Better to let the parent do the adding.
}
}
}
========================= ============================
編輯迴應評論
在ActionScript中,靜態方法是例外,不是規則。因此,要創建一個總線,您可以按照以下方式更改代碼。評論解釋了代碼。
package
{
import Bus;
import flash.display.Sprite;
import flash.events.Event;
import flash.display.Stage;
public class Main extends Sprite
{
public function Main()
{
// Add a new member variable to the Main class.
var bus:Bus = new Bus();
// we can call methods of our Bus object.
// This imaginary method would tell the bus to drive for 100 pixels.
bus.drive(100);
// We would add the bus to the display list here
this.addChild(bus);
// Assuming we have access to the stage we position the bus at the center.
if(stage != null){
bus.x = stage.stageWidth/2;
bus.y = stage.stageHeight/2;
}
}
}
}
這就是你如何創建你的類的實例並訪問它,而不需要任何靜態方法。「new」關鍵字實際上是調用類的構造函數方法的快捷方式,它返回該類的新實例。調用「new」的父項將該實例作爲子項並有權調用其所有公共方法和屬性。
您錯過了Bus.addBus(),嘖嘖嘖嘖 – Ryan 2011-12-15 09:51:29