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.
+3
A:
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;
James Fassett
2009-08-31 00:14:23
A:
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.
Amarghosh
2009-09-01 05:53:32