I'm new to AS3 and I come from a Java background. In AS3, I have an initialized static const Object, PRESETS, and tried to access it in the constructor, but I get an error saying that the constant is null. Does a class constructor get called before the constants are initialized? I expect the constant to be ready to use before the constructor was called. Can anyone explain what is happening here? I would like to try and make this work.
My code below:
public class TteColor {
// This is the constant I'm trying to access from the constructor.
public static const PRESETS:Object = {
"WHITE": new TteColor("#FFFFFF"),
"BLACK": new TteColor("#000000"),
"GRAY": new TteColor("#808080"),
"RED": new TteColor("#FF0000"),
"GREEN": new TteColor("#00FF00"),
"BLUE": new TteColor("#0000FF"),
"YELLOW": new TteColor("#FFFF00"),
"CYAN": new TteColor("#00FFFF"),
"MAGENTA": new TteColor("#FF00FF")
};
public static const COLOR_REGEX:RegExp = /^#[\dA-Fa-f]{6}$/;
public var intValue:int;
public var strValue:String;
public function TteColor(color:String, defaultColor:TteColor = null) {
trace("trace0");
if (color != null && color.search(COLOR_REGEX) >= 0) {
trace("trace1");
strValue = color.toUpperCase();
intValue = uint("0x" + strValue.substring(1));
} else {
trace("trace2");
if (!defaultColor) {
trace("trace2.1");
trace("PRESETS: " + PRESETS);
defaultColor = PRESETS["WHITE"]; // PRESETS constant is still null here?
}
trace("trace3");
strValue = defaultColor.strValue;
intValue = defaultColor.intValue;
Logger.warning("Incorrect color value. Defaulting to: " + strValue);
}
}
}
Output:
The output shows that the PRESETS constant is null.
trace0
trace2
trace2.1
PRESETS: null
TypeError: Error #1009: Cannot access a property or method of a null object reference.
Changing to static variable
I change the PRESETS constant to static variable and statically initialize the values. This works fine as it should. Why would constant fails when static variable works?
// Statically initialize PRESETS
{
PRESETS = new Object();
PRESETS["WHITE"] = new TteColor("#FFFFFF");
PRESETS["BLACK"] = new TteColor("#000000"); PRESETS["GRAY"] = new TteColor("#808080");
PRESETS["RED"] = new TteColor("#FF0000");
PRESETS["GREEN"] = new TteColor("#00FF00");
PRESETS["BLUE"] = new TteColor("#0000FF");
PRESETS["YELLOW"] = new TteColor("#FFFF00");
PRESETS["CYAN"] = new TteColor("#00FFFF"); PRESETS["MAGENTA"] = new TteColor("#FF00FF");
}
// Changed from constant to static class variable. This works fine.
public static var PRESETS:Object;