Comparing Objects in Actionscript [REVISITED]

Posted on March 28, 2008. Filed under: Actionscript 3, Programming |

Alright, I have found a flaw in the whole comparing objects in Actionscript.

As per my pervious post on the subject, it turns out that all logic operators function as would be expected when defining custom boolean logic behaviour for an object. However, the equality operator seems to be different. The equality seems to never work like it should when providing valueOf methods for your objects. See below.

Example:

var obj1 : Object = new Object();
var obj2 : Object = new Object ();
// this traces completely inaccurate results for each comparison (as it should).
traceComparisons(obj1, obj2);
obj1.valueOf = function () { return 1; };
obj2.valueOf = function () { return 1; };
// this traces correct comparisons, using the valueOf() method of each object.
traceComparisons(obj1, obj2);

function traceComparisons (a : Object, b : Object) : void
{
    trace("a == b :" + (a == b));
    trace("a < b : " + (a < b));
    trace("a > b : " + (a > b));
    trace("a <= b : " + (a <= b));
    trace("a >= b : " + (a >= b));
    trace(" ");
}

// output
// a == b : false
// a < b : false // a > b : false
// a <= b : true // a >= b : true

Make a Comment

Make a Comment: ( None so far )

blockquote and a tags work here.

Liked it here?
Why not try sites on the blogroll...