代码之家  ›  专栏  ›  技术社区  ›  jedierikb grijalvaromero

设置actionscript 3超类变量

  •  1
  • jedierikb grijalvaromero  · 技术社区  · 16 年前

    在AS3中,如果我有这样一个类:

    public class dude
    {
    //default value for a dude
    protected var _strength:Number = 1; 
    public function dude( ):void
    {    super( );
         //todo... calculate abilities of a dude based on his strength.
    }
    }
    

    public class superDude extends dude
    {
    
    public function superDude( ):void
    {
       _strength = 100;
       super( );
       trace( "strength of superDude: " + _strength );
    }
    }
    

    超人的力量是1 . 我希望在子类中设置的变量(在调用超类构造函数之前)保持不变。

    有没有一种方法可以在子类构造函数中分配类变量,而这些子类构造函数不会被超类构造函数重写?或者我应该把它们作为构造函数变量来传递?

    3 回复  |  直到 16 年前
        1
  •  4
  •   Cornel Creanga    16 年前

    将\u strength设置为100后调用super();此指令将从超类调用构造函数,该超类将变回1(变量初始化发生在构造函数中)。这是无法避免的,我认为应该在初始化变量之前调用super()。

        2
  •  1
  •   Kayes    16 年前

    首先。。默认的超类构造函数(不接受任何参数)是从子类构造函数隐式调用的。所以你不需要显式地调用它。

    如果超类构造函数接受参数,那么您需要显式调用它,并且该调用必须是子类构造函数中的第一个语句。

        3
  •  0
  •   Triynko    12 年前

    在回答凯斯的问题时,我必须提到,不应该总是先叫“超级”。

    现在的 尽快初始化(即,在调用super之前),因为它们可能需要对一个被重写的方法可用,而该方法可能被super类构造函数调用。如果在调用super之前没有初始化这些变量,那么重写的方法将无法使用它们。另一方面,应该在需要访问任何stage实例之前调用super。

    类,但初始化 超级的

    public class GUIControlSubclass extends GUIControl
    {
        private var _param:String;
        public function GUIControlSubclass( param:String )
        {
            _param = param; //variable of this class must be assigned before calling super, so it's available to override of initLayout
            _backgroundColor = 0xffffff; //it is incorrect to assign protected/public variable of super class here, since it will be reset by super call
            super(); //super class constructor will call initLayout, which will call this subclass's override of it; super class constructor itself should call it's own "super" method *before* calling initLayout, to ensure stage instances are constructed and available to initLayout
        }
    
        override protected function initLayout():void
        {
            super.initLayout();
            //IF _param WAS NOT SET **BEFORE** CALLING SUPER IN THE CONSTRUCTOR, ITS VALUE WOULD BE NULL HERE, SINCE SUPER TRIGGERS THIS METHOD, THEREFORE _param MUST BE ASSIGNED BEFORE SUPER IS CALLED
        }
    }