変数と定数
変数はvar,定数はconstで宣言します。変数は変更できますが、定数は変更不可です。
変数
<アクセス指定子> var <変数名>:<型> = <初期値>;
定数
<アクセス指定子> const <変数名>:<型> = <初期値>;
サンプル
<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete = "main()" > <mx:Panel title="" width="200" height="200"> <mx:TextArea id="stdout" width="200" height="200" /> </mx:Panel> <mx:Script><![CDATA[ // 定数と変数 public var hello:String = "hello"; public const world:String = "world!"; // メイン public function main():void { stdout.text += hello + " " + world + "\n"; // 変数の値を変更 hello = "foo"; stdout.text += hello + " " + world + "\n"; } ]]></mx:Script> </mx:Application>
定数の値を変更。
コンパイルでエラーになります。
<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete = "main()" > <mx:Panel title="" width="200" height="200"> <mx:TextArea id="stdout" width="200" height="200" /> </mx:Panel> <mx:Script><![CDATA[ public const world:String = "world!"; // メイン public function main():void { world = "hoge"; } ]]></mx:Script> </mx:Application>
コンパイルした結果:
xxx/edit_const.mxml(15): Error: 定数として指定した変数への代入が無効です。 world = "hoge";