Extending Actionscript implicit getter & setters.

Here’s something i only just noticed. If you overwrite either a getter or setter in a subclass of a class with both, but don’t provide a hook for the other one, then the property will become either read or write only. For example:

MyClass{
var _i:Number
public function get i ():Number{
return _i
}
public function set i(num:Number):Void{
this._i=num
}
}

Will produce the following expected behaviour:

var myClass = new MyClass()
myClass.i=10
trace(myClass.i) //traces 10

In the subclass we overwrite the setter with some new behaviour:

mySubClass extends MyClass{
public function set i(num:Number):Void{
this._i=num*2
}
}

Will produce the following not so expected behaviour:

var myClass = new MySubClass()
myClass.i=10
trace(myClass.i) //traces undefined

Which means the property i has become write only. To keep the property read and write you need to copy the getter into the sub class:

mySubClass extends MyClass{
public function get i ():Number{
return _i
}
public function set i(num:Number):Void{
this._i=num*2
}
}

And you then get the following:

var myClass = new MyClass()
myClass.i=10
trace(myClass.i) //traces 20

I know it makes a kind of sense, but it does mean you have to be careful you’re not changing the signature of your subclasses, as they dont behave exactly as you might expect.

  1. #1 by Tony on May 21st, 2006 - 11:43 pm

    Thanks for the tip, but it looks like you have a typo in your ‘returns’ (_i)

  2. #2 by Phil on May 22nd, 2006 - 12:49 am

    Curses fixed.
    This is exactly why i don’t edit actionscript in my blog software. The autocompletion is terrible ;)

  3. #3 by maliboo on May 22nd, 2006 - 8:33 pm

    Because of AS1 bytecode nature of AS2 getters/setters aren’t inherited partialy. If you define get function, you must also define set function, and vice versa. Subclass in this case define “i” property as:


    //From ASV:
    var _local2 = MySubClass.prototype;
    _local2.__set__i = function (num) {
    this._i = num * 2;
    return (this.__get__i());
    };
    _local2.addProperty("i", function () {
    }, _local2.__set__i)); //Getter function is omitted

  1. No trackbacks yet.

Comments are closed.


  • SetPageWidth