AS3从子类访问父类的变量
我正在尝试从父级的子级分配父级的变量,但
//Parent
public class Main extends Sprite
{
public var selectedSquare:Sprite;
public function Main()
{
//inits and adds new Square child class to display list
}
...
-------
//Child
public function dragSquare(evt:MouseEvent):void
{
Sprite(parent).selectedSquare = this; //evil doesn't work!
parent.addChild(this);
this.startDrag();
}
我收到此错误,但我正在将父级从 displayObjectContainer 转换为 Sprite,所以我不知道为什么它不起作用。
1119:访问可能未定义的 属性 selectedSquare 通过 a 静态类型的引用 flash.display:精灵。
i'm trying to assign a parent's variable from the parent's child
//Parent
public class Main extends Sprite
{
public var selectedSquare:Sprite;
public function Main()
{
//inits and adds new Square child class to display list
}
...
-------
//Child
public function dragSquare(evt:MouseEvent):void
{
Sprite(parent).selectedSquare = this; //evil doesn't work!
parent.addChild(this);
this.startDrag();
}
i'm receiving this error, but i'm casting parent from displayObjectContainer to a Sprite so i have no idea why it's not working.
1119: Access of possibly undefined
property selectedSquare through a
reference with static type
flash.display:Sprite.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该将父对象转换为 Main 而不是 Sprite,因为 Sprite 不会有任何对“selectedSquare”的引用。如果 Main 要扩展 MovieClip,这不会成为问题,因为 MovieClip 可以动态创建引用。
建议对子函数的修改:
You should cast parent as a Main rather than a Sprite, since a Sprite won't have any references to a "selectedSquare". If Main were to extend MovieClip, this wouldn't be a problem, since MovieClips can have dynamically created references.
Proposed modification to child function:
这可能不起作用的另一个原因是您在将子级添加到父级的显示列表之前尝试使用
parent
属性。第二行让我担心。在此代码中,当前对象 (
this
) 必须 作为子对象添加到父对象 (Main
) 中,以便第一行能够正常工作。因此,要么当前对象还不是父对象的子对象,在这种情况下您需要修改代码。或者,第二行是不必要的(因为
this
已经是Main
的子级,这就是为什么this.parent
或只是parent
,按预期工作)。不过,我相信您的代码可能设置得很好。您只是不需要第二行,因为它完全是多余的。
我希望这有帮助!如果您想让我澄清任何事情,请告诉我。
(当然,这是假设您还不知道所有这些,并且没有使用多余的
addChild
调用来执行某种疯狂、神秘、怪异的魔术。魔术师永远无法告诉您!)Another reason that this may not work is that you're attempting to use the
parent
property right before adding the child to the parent's display list.That second line is what worries me. In this code, the current object (
this
) must already be added as a child to the parent object (Main
) for the first line to work properly. So, either the current object is not yet a child of the parent object, in which case you need to revise your code.Or, the second line is unnecessary (because
this
is already a child ofMain
, that's whythis.parent
, or justparent
, works as expected).I believe, though, that your code is probably set up well. You just don't need that second line, as it's completely redundant.
I hope that helps! Let me know if you want me to clarify anything.
(This is, of course, assuming you didn't already know all of this and aren't doing some sort of insane, arcane, weird magic with the redundant
addChild
call. You never can tell with magicians!)