我是 AS3 的新手,我来自 Java 背景。在 AS3 中,我有一个已初始化的静态 const 对象 PRESETS,并尝试在构造函数中访问它,但我收到一个错误消息,指出该常量为空。在初始化常量之前是否调用了类构造函数?我希望常量在调用构造函数之前就可以使用了。谁能解释这里发生了什么?我想尝试完成这项工作。
我的代码如下:
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);
}
}
}
输出:
输出显示 PRESETS 常量为空。
trace0
trace2
trace2.1
PRESETS: null
TypeError: Error #1009: Cannot access a property or method of a null object reference.
更改为静态变量
我将 PRESETS 常量更改为静态变量并静态初始化值。这可以正常工作。当静态变量起作用时,为什么常量会失败?
// 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;