4 properties readonly actionscript-3
AS3中的许多库类都具有"只读"属性.是否可以在自定义as3类中创建此类属性?换句话说,我想创建一个具有公共读取但是私有集的属性,而不必为我想要公开的每个属性创建复杂的getter/setter系统.
只读的唯一方法是使用AS3 的内置get
和set
功能.
编辑: 原始代码只写.对于只读,只需使用get
而不是set
这样:
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++; }
}
}
Run Code Online (Sandbox Code Playgroud)
这允许你像这样访问foo:
var tc:TestClass = new TestClass();
trace(tc.foo);
tc.incrementFoo();
trace(tc.foo);
Run Code Online (Sandbox Code Playgroud)
以下是仅供写作参考的原件:
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; }
}
}
Run Code Online (Sandbox Code Playgroud)
这将允许您在外部设置_foo的值,如下所示:
var tc:TestClass = new TestClass();
tc.foo = 5;
// both of these will fail
tc._foo = 6;
var test:int = tc.foo;
Run Code Online (Sandbox Code Playgroud)