I'm trying to create a property that can be set
by extending classed and read
publicly.
I couldn't think of a good naming convention for a protected
property with a public
getter, so I tried to do this:
public function get name():String{ return _name; }
protected function set name(string:String):void
{
_name = strin开发者_Python百科g;
}
However I get the error (when trying to set
name
in an extending class):
1178: Attempted access of inaccessible property name through a reference with static type testing:TestComponent.
1059: Property is read-only.
If I change the setter to public
, it works fine.
As far as I know AS3 doesn't allow you to mix and match, both accessors should be the same.
I generally don't supply a setter to make the property read only, and directly set _name
internally. Because it's protected, it will be accessible to descendants.
You can use it like below.
public class Test extends Object {
protected var _name:String;
public function get name():String {return _name;}
}
public class Test2 extends Test {
public function set name(s:String):void {
this._name = s;
}
}
I took a slightly different approach to achieve what I wanted:
public function get name():String{ return _name; }
public function set name(string:String):void
{
if(!_name.length)
_name = string;
else throw new Error("Property \"name\" can only be defined once.");
}
Now name
will be defined within the extending class, but can't be set from then on.
精彩评论