天天看點

Dynamic Class & Sealed Class

從是否可以動态的添加執行個體屬性或方法,可以将類分為動态類(Dynamic Class)和密封類(Sealed Class)。動态類生成的執行個體可以在運作時動态添加屬性,而密封類則不可以。所謂的動态的非動态的區分僅存在于編譯階段。for..in 與for each ... in隻能周遊動态類的動态屬性(運作以下例子可以檢視效果)

package com.test

{

  public    dynamic class DynamicClassExample

  {

    public function DynamicClassExample()

    {

    }

    private var _name:String;

    private var _age:int;

    public var test:String = "test";

    public function set name(val:String):void

      this._name = val;

    public function get name():String

      return this._name;

    public function set age(val:int):void

      this._age = val;

    public function get age():int

      return this._age;

  }

}

  public class SealedClassExample

    public function SealedClassExample()

<?xml version="1.0" encoding="utf-8"?>

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" horizontalAlign="center" verticalAlign="middle">

  <mx:Script>

    <![CDATA[

      import com.test.SealedClassExample;

      import com.test.DynamicClassExample;

      private function testDynamic():void

      {

        var dy:DynamicClassExample = new DynamicClassExample();

        dy.age = 10;

        dy.name = "Dynamic"

        dy.newAddProp = "Hello,Dynamic class!";

        dy.url = "com.test.Dynamic.url";

        for( var k in dy)

        {

          tad.text +=k+":"+dy[k]+"\n";

        }

      }

      private function testSealed():void

        var seal:SealedClassExample = new SealedClassExample();

        seal.age = 10;

        seal.name = "seal";

        //seal.newAddProp = "You had better not do that!";

        //seal.url = "com.test.sealed.url";

        // if the below code is not commented,the compiler will indicate the error:access undefined property.

        for( var k in seal)

          tas.text +=k+":"+seal[k]+"\n";

    ]]>

  </mx:Script>

  <mx:HDividedBox width="100%" height="100%" horizontalAlign="left" verticalAlign="top">

    <mx:VBox width="50%" height="100%">

      <mx:Button label="testDynamic" click="testDynamic()"/>

      <mx:TextArea text="" id="tad" width="379" height="460"/>

    </mx:VBox>

      <mx:Button label="testSealed" click="testSealed()"/>

      <mx:TextArea text="" id="tas" width="329" height="470"/>

  </mx:HDividedBox>

</mx:Application>

下一篇: class

繼續閱讀