即使我导入了 Stage 类,为什么我的 Actionscript 3 类中的 stage 未定义?
package {
import flash.display.Stage;
public class MyGlobal {
public static var CX:Number = stage.stageWidth / 2;
public static var CY:Number = stage.stageHeight / 2;
}
}
错误是“1120:访问未定义的属性阶段。”
为什么?
package {
import flash.display.Stage;
public class MyGlobal {
public static var CX:Number = stage.stageWidth / 2;
public static var CY:Number = stage.stageHeight / 2;
}
}
The Error is "1120: Access of undefined property stage."
WHY?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如前所述,stage 是从 DisplayObject 继承的类的属性。在将舞台添加到舞台(通常通过 DisplayObjectContainer 的 addChild 方法)之前,舞台对类不可用。
As mentioned, stage is a property of classes that inherit from DisplayObject. Stage is not available to a class until it has been added to the stage, generally via the addChild method of a DisplayObjectContainer.
stage 属性仅可用于显示已添加到舞台的对象。您的类不是从 DisplayObject 继承的,因此您的类不存在 stage 属性。即使您的类确实继承自 DisplayObject,也需要通过父显示对象的 addChild() 将其添加到舞台。
如果您的类并不是要成为显示对象,而是需要用于测量或其他属性的舞台对象,请将其作为参数发送给构造函数。
否则,让你的类继承 DisplayObject,然后你必须添加一个事件侦听器,以便在将对象添加到舞台时:
在 onAddedToStage() 方法中,舞台现在可用(编辑:只要舞台属性可用最顶层的父容器已添加到舞台中)。
The stage property is only available to display objects that have been added to the stage. Your class does not inherit from DisplayObject, so the stage property does not exist for your class. Even if your class did inherit from DisplayObject, it needs to be added to the stage via addChild() from a parent display object.
If your class is not meant to be a display object, but needs the stage object for measurements or other properties, send it as an argument to the constructor.
Otherwise, make your class inherit DisplayObject, then you have to add an event listener for when the object is added to the stage:
In the onAddedToStage() method, stage will now be available (EDIT: the stage property will be available as long as the top most parent container has been added to the stage).
我通过将阶段对象引用传递给类的构造函数来解决这个问题。老实说,我不喜欢这个解决方案,因为你必须通过这个阶段,但这是我看到的最简单的方法。
这就是我在构造函数中所做的:
I solved this by passing stage Object reference to the constructor of the class. I honestly don't like the solution because you have to pass the stage but its the simplest way i saw.
this is what i did in the constructor:
Sam的回答其实是很正确的。最简单的解释是,stage 是一个实例,而不是类成员。
如果您的字段未声明为静态,您将能够访问 stage。但您可能会收到空引用错误;)
The answer from Sam is actually quite right. The easiest explanation is that
stage
is an instance and not a class member.If your fields were not declared static, you would be able to access stage. But you would probably get a null-reference error ;)