如何定義對象定義內的屬性,以便我可以在構造函數中使用它?JavaScript - 如何定義對象定義中的屬性
例如: 當我在屬性'x'和'y'的命名空間WindowManager中定義一個對象Window時,我想使用WindowManager.Window.DEFAULT_X和WindowManager.Window.DEFAULT_Y來處理未定義的/ null參數在我的構造函數中。就像這樣:
var WindowManager = {
Window: {
get DEFAULT_X() {
return 0;
},
get DEFAULT_Y() {
return 0;
},
constructor: function Window (xPos, yPos) {
this.x = xPos || WindowManager.Window.DEFAULT_X;
this.y = yPos || WindowManager.Window.DEFAULT_Y;
},
prototype: {
x: undefined,
y: undefined
}
}
};
WindowManager.Window = WindowManager.Window.constructor;
我將如何改變我的代碼,這樣我就可以使用這些「靜態」屬性的內部構造和維修一些幾分優雅的代碼?
我不希望我的代碼看起來是這樣的:
WindowManager.Window.__defineGetter__ ("DEFAULT_X", function getDEFAULT_X() {
return 0;
});
// ...
WindowManager.Window.constructor = function Window (xPos, yPos) {
this.x = xPos || WindowManager.Window.DEFAULT_X;
this.y = yPos || WindowManager.Window.DEFAULT_Y;
};
'DEFAULT_X' /'Y'會改變嗎?我不完全理解爲什麼重要的是讓它們以getter爲基礎,如果所有的getter都會返回0. – apsillers 2014-09-30 13:31:32
'this.x = xPos || WindowManager.Window.DEFAULT_X;'如果'xPos'爲'0',那麼'this.x'將採用默認值,通常最好手動測試'undefined'和'null':if(typeof foo == =「undefined」|| foo === null)'。哦,javascript ...... – Hoffmann 2014-09-30 13:58:29
的樂趣DEFAULT_X和DEFAULT_Y被定義爲getters,所以它們的行爲就像常量。有沒有更好的方法來實現這一目標? 我用||像這樣的操作符來縮短示例代碼。我知道JavaScript的'美'。 – 2014-09-30 14:29:12