开发者

When extending an object; why not use "this" instead of "super" when changing object members

This question is posed from an ActionScript context but could be from a Java one equally.

The code I am using as a sample comes from adobe.com/devnet/flex/articles/flex4_skinning.html. In the code extract below the NoteCard class has an enabled and a disabled state which it inherits from the SkinnableComponent class. My question is; why in the enabled setter do we call super.enabled = value; and not this.enabled = value;. We have created our NoteCard object instance from the constructor and should we not then be able to set the value of the enabled member using the "this" keyword. If you do swap super for this no errors are shown by the compiler but the code fails to work.

    package
    {

     import spa开发者_如何学运维rk.components.supportClasses.SkinnableComponent;

      public class NoteCard extends SkinnableComponent
      {
       public function NoteCard()
       {
        super();
       }


      override public function set enabled(value:Boolean) : void
      {
       if (enabled != value)
       invalidateSkinState();

      super.enabled = value;
      }

      override protected function getCurrentSkinState() : String
      {
       if (!enabled)
       return "disabled";

      return "normal"
      }

     }
    }        


If we'll use:

  override public function set enabled(value:Boolean) : void
  {
   if (enabled != value)
   invalidateSkinState();

  enabled = value;
  }

We'll run into infinite loop. This line:

enabled = value;

will call the same setter again and again.


In this special case you override a setter for a class. You can implement your own additional code to handle the newly set value, but the code from your superclass should also be called, because you may not know, what the base class setter will do (may be set a private variable with a value). You have to call super.setterName = value to assure this. If you would call with this you would call your implemented setter in an infinite loop. You may omit the super call, if you are sure, this isn't necessary.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜