How can I refer to a global class from a class of the same name in ActionScript?
Due to requirements outside of my control (don't ask, this is ridiculous) I need to create an AS3 class named Math that references the Global AS Math class. So for example:
package my.package
{
public class Math
{
public static function pow( a:Number, b:Number ):Number {
// How do I call the Global.as$Math#pow(..) function?
return Math.pow(a,b);
}
}
}
The above code is clearly wrong - leads to infinite recursion. I am not sure how to say that I want to delegate the Global.as $ Math class and not this Math class ...
My current awkward solution is to delegate to another class (not named Math) that goes into the Global Math class. Is there a better way to do this?
Thanks!
a source to share
Here's another way that came into my mind after reading Josh Tynjala's post about how a package in ActionScript is just a layer of abstraction over namespaces:
public class Math
{
namespace globalNs = "";
public static function pow( a:Number, b:Number ):Number
{
return globalNs::Math.pow(a, b);
}
}
GlobalNs :: Math.pow explicitly refers to the top-level Math class.
a source to share
Save a static reference to the Flash Math player object and use it in all your static methods:
package test
{import flash.utils.getDefinitionByName;
public class Math
{
private static var _flashMath:Class = Class(getDefinitionByName("Math"));
public static function pow( a:Number, b:Number ):Number
{
return _flashMath.pow(a, b);
}
}
}
a source to share
Try using the AS3 namespace to reference the AS3 Math object. Or, your class can simply extend the Math object, and it will automatically have all the functions of the Math object without having to rewrite all those wrapper functions.
a source to share
As a small follow-up to the affixers answer, you cannot just extend the AS3 Math object and have all the functionality that has been ingrained. Static methods are lost when extending an object because they are statically bound to the object that defines them. Also, you cannot extend a class with the same name. However, you may have some success with a namespace solution, although I'm not sure if it will work with static methods, I would be interested to see your results.
a source to share
Math is a special case in AS3 because it doesn't really have to be global, but it is. As far as I can tell, it doesn't have a namespace. The solution you come up with for routing through a different class is actually very clever. But you know the solution is actually to name the class Math2 or MathHelper or MathUtils, not Math. Please tell me what reason is out of your control! Ignorance is killing me !!!
a source to share