Overriding valueOf in ActionScript

This is a response to Maploop’s weblog, where he has an entry talking about addition and the $ symbol. The comments there seem to be broken, so I’m re-posting on my blog here.

Why not just override valueOf, and then you can use them as custom addition datatypes? Haven’t tried myself, so don’t know if it works or not…

:: tries ::

Hrm, works in AS1:

function Cow()
{
}
Cow.prototype.valueOf = function()
{
        return 2;
};

var a = new Cow();
var b = new Cow();
trace(a + b); // 4

Now AS3…

:: tries ::

Yep, works in AS3 as well:

package
{
        public class Cow
        {
                public function Cow()
                {
                }

                public function valueOf():Number
                {
                        return 2;
                }
        }
}

var a:Cow = new Cow();
var b:Cow = new Cow();
trace(a + b); // 4

2 Replies to “Overriding valueOf in ActionScript”

Comments are closed.