This website uses cookies to improve user experience. By using our website you consent to all cookies in accordance with our Cookie Policy. X

Strict comparison to a class type without the use of 'is' or 'instanceof'

In ActionScript2 and 3 you can always check if an object belongs to a certain class - in AS2 the keyword for this is instanceof while in AS3 its is and both of them do a pretty fine job, however they also return 'true' when checking a base class against a subclasses. In other words MovieClip check against Sprite will get us 'true':
var mc:MovieClip = new MovieClip();
trace(mc is Sprite); //true
This raises a question: what if we want to check against a specific class and only that one class? Solutions are two:
1. The getQualifiedClassName function.
Which is the most straightforward answer - we extract the class name as a String and compare it against the name we are searching for.
var mc:MovieClip = new MovieClip();
trace(getQualifiedClassName(mc) == "MovieClip"); //true
trace(getQualifiedClassName(mc) == "Sprite"); //false
2. Comparing the constructors.
This is a bit more advanced topic that only works in AS3. It is not always clearly stated but each object in ActionScript3 has a 'constructor' field which always holds the reference to the constructor used in creation process of an object and because in ActionScript there can be only one constructor, it just a matter of comparing them:
var mc:MovieClip = new MovieClip();
var con:Object = MovieClip.prototype.constructor;
trace(mc.constructor == con); //true
However there are few things worth pointing out here:
- because 'prototype' and 'constructor' are created dynamically, their access time is slower in comparison to the getQualifiedClassName function.
- however with a reasonably long loop and local variable holding the constructor reference, execution time can be even as twice as fast.
- mc.constructor in FlashDevelop (but not Flash Professional) will most likely throw an error, which needs to worked around by casting mc to the Object class:
var con:Object = MovieClip.prototype.constructor;
trace((mc as Object).constructor == con); //true
Unfortunately this will decrease the execution time by around 10%.

Name:
Comment:
Confirm the image code:confirm image