R – Add setter in a prototype in Flex

actionscript-3apache-flexprototype

In Flex, you can add functions to the prototype of a Class; but how do you add a setter?

For example, with A some (non-dynamic) class, you can do this:

var o:Object = new A();
A.prototype.myFunction = function():void{trace("foo");}
o.foo();

And that will call the foo function. But how could you add a setter, so that setting the property calls the setter (just like it would if you declared the setter in the "normal" way on the A class). So what I want is something like this:

// doesn't work!    
A.prototype["set myProperty"] = mySetter; 
o.myProperty = "test"; // should call mySetter

PS: Manipulating the prototype is an unusual thing to do in Flex, and not something I'd recommend in general. But for the sake of this question, just assume that there is a reason to dynamically add a setter.

Best Answer

ActionScript 1/2 supported this by calling addProperty(name, getter, setter). This could be done on individual objects or on a prototype. AS3 doesn't support this, even with the "-es" flag.

For reference, here's an example of how it used to be done:

var A = function() {};

A.prototype.addProperty("myProp", 
    function() { 
        trace("myProp getter: " + this._myProp); 
        return this._myProp; 
    }, 
    function(value) {
        trace("myProp setter: " + value); 
        this._myProp = value; 
    });

var a = new A();
a.myProp = "testing";
var x = a.myProp;