我是AS3的新手,來自Java背景。在AS3中,我有一個初始化的靜態常量對象PRESETS,並試圖在構造函數中訪問它,但是我得到一個錯誤,說該常量爲null。在常量初始化之前調用類構造函數嗎?我希望這個常量在構造函數被調用之前就可以使用了。任何人都可以解釋這裏發生了什麼?我想嘗試做這項工作。在Actionscript中,靜態常量初始化之前調用類構造函數嗎?
我以下代碼:
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;
哦。咄!德普時刻就在那裏。謝謝你指出。 – nikeairj