简体   繁体   中英

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?

    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.

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. 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). That way you can use DisplayObject's parent property to get to 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;
}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM