[英]AS3 what is the correct way of making a variable accessible to a child class / object
When you initialize a new object, how can that class have access to a variable from the parent? 初始化新对象时,该类如何从父对象访问变量?
In this case Blob needs to be able to access scale? 在这种情况下,Blob需要能够访问规模吗?
public class Parent
{
protected var scale:int = 32;
public function Parent()
{
var shape = new Blob(15, 55);
}
}
-- -
public class Blob
{
private var _xp:int
private var _yp:int
private var _worldX:int;
private var _worldY:int;
public function Blob(x:int, y:int)
{
_xp = x;
_yp = y;
_worldX = _xp * scale;
_worldY = _yp * scale;
}
public function get worldX():int {
return _worldX;
}
} }
The extends keyword is what you're looking for. extends关键字是您正在寻找的。
public class Blob extends Parent{
/* This class is now a subclass of Parent */
It is not exactly clear what you want to accomplish. 目前还不清楚你想要完成什么。 In your example you probably need to pass a reference to Parent object in Blob constructor and make scale public.
在您的示例中,您可能需要在Blob构造函数中传递对父对象的引用并将比例设置为public。 You can avoid passing a reference if both Blob and Parent are in display list and Parent contains Blob (that is Blob is some descendant of DisplayObject and Parent is DisplayObjectContainer).
如果Blob和Parent都在显示列表中并且Parent包含Blob(即Blob是DisplayObject的一些后代而Parent是DisplayObjectContainer),则可以避免传递引用。 That way you can use DisplayObject's parent property to get to Parent.
这样,您可以使用DisplayObject的父属性来获取Parent。
public class Parent
{
public var scale:int = 32;
public function Parent()
{
var shape = new Blob(15, 55, this);
}
}
-- -
public class Blob {
private var _xp:int
private var _yp:int
private var _worldX:int;
private var _worldY:int;
private var _parent:Parent;
public function Blob(x:int, y:int, parent:Parent)
{
_xp = x;
_yp = y;
_parent = parent;
_worldX = _xp * parent.scale;
_worldY = _yp * parent.scale;
}
public function get worldX():int {
return _worldX;
}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.