Creating read-only properties in Actionscript 3

11,919

Solution 1

The only way to have a read only is to use the built-in get and set functions of AS3.

Edit: original code was write only. For read only just use get instead of set like so:

package
{

import flash.display.Sprite;

public class TestClass extends Sprite
{
    private var _foo:int = 5;

    public function TestClass() {}

    public function get foo():int{ return _foo; }
    public function incrementFoo():void { _foo++; }
}

}

Which allows you to access foo like so:

var tc:TestClass = new TestClass();
trace(tc.foo);

tc.incrementFoo();
trace(tc.foo);

Here is the original for reference on write only:

package
{

import flash.display.Sprite;

public class TestClass extends Sprite
{
    private var _foo:int;

    public function TestClass() {}

    public function set foo(val:int):void{ _foo = val; }
}

}

That will allow you to set the value of _foo externally like so:

var tc:TestClass = new TestClass();
tc.foo = 5;

// both of these will fail
tc._foo = 6;
var test:int = tc.foo;

Solution 2

You cannot have public set and private get with the same name. But as James showed, you can rename the setter into something else and make it private to get a read only property.

Solution 3

Well can't you do like this?

package
{

import flash.display.Sprite;

public class TestClass extends Sprite
{
    private var _foo:int = 5;

    public function TestClass() {}

    public function get foo():int{ return _foo; }
    public function set foo(value:int):void{ throw new Error("The variable foo is read-only"); }
}

}
Share:
11,919
Admin
Author by

Admin

Updated on June 19, 2022

Comments

  • Admin
    Admin almost 2 years

    Many library classes in AS3 have "read only" properties. Is it possible to create such properties in custom as3 classes? In other words, I want to create a property with a public read but a private set without having to create a complex getter/setter system for every property I want to expose.