Actionscript 3 在外部类函数中声明Stage并在其他类中使用它?

Actionscript 3 在外部类函数中声明Stage并在其他类中使用它?,actionscript-3,positioning,stage,Actionscript 3,Positioning,Stage,我试图实现的是制作一个“centerItem”——将对象集中在舞台上的方法。我想在我的Misc类文件中添加此方法,并在我的应用程序中随处使用它。我已经像下面那样尝试过了,但没有成功: public static function centerItem(item:*):void { item.x = (stage.stageWidth - item.width) >> 1; item.y = (stage.stageHeight - item.height) >&

我试图实现的是制作一个“centerItem”——将对象集中在舞台上的方法。我想在我的Misc类文件中添加此方法,并在我的应用程序中随处使用它。我已经像下面那样尝试过了,但没有成功:

public static function centerItem(item:*):void
{
    item.x = (stage.stageWidth - item.width) >> 1;
    item.y = (stage.stageHeight - item.height) >> 1;
}
并这样称呼它:

Misc.centerItem(myObjectToPlaceOnStage);

但当我尝试时,它只会给我一个错误。我已经在网上看过了,但没有找到任何建设性的解决方案。我希望有人能找到解决方案/黑客

如果您的对象已添加到stage上,您可以访问其stage属性:

public static function centerItem(item:DisplayObject):void
{
    item.x = (item.stage.stageWidth - item.width) >> 1;
    item.y = (item.stage.stageHeight - item.height) >> 1;
}

顺便说一句,我已经将您的item参数键入到了
DisplayObject
,因此您可以确定它具有
宽度
高度
阶段
属性。

if(item.hasOwnProperty(“阶段”){item.x=(item.stage.stageWidth-item.width)>1;item.y=(item.stage.stagewhight-item.height)>>1;}添加了hasProperty,以100%确保它被添加到stage(我不确定这是否是正确的方法,但可以,仍然感谢^^^)否。不要使用addOwnProperty,它将具有属性。您可以使用
item.stage!=改为null