2014-09-30 39 views
0

如何定義對象定義內的屬性,以便我可以在構造函數中使用它?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; 
}; 
+0

'DEFAULT_X' /'Y'會改變嗎?我不完全理解爲什麼重要的是讓它們以getter爲基礎,如果所有的getter都會返回0. – apsillers 2014-09-30 13:31:32

+0

'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

+0

的樂趣DEFAULT_X和DEFAULT_Y被定義爲getters,所以它們的行爲就像常量。有沒有更好的方法來實現這一目標? 我用||像這樣的操作符來縮短示例代碼。我知道JavaScript的'美'。 – 2014-09-30 14:29:12

回答

0

要做到這一點,最好的辦法可能是使用封閉

var Window; 

(function() { 
    var DEFAULT_X= 100; 
    var DEFAULT_Y= 100; 
    Window= function (x, y) { 
     if (typeof x === "undefined" || x === null) 
     this.x= DEFAULT_X; 
     else 
     this.x = x; 

     if (typeof y === "undefined" || y === null) 
     this.y= DEFAULT_Y; 
     else 
     this.y = y; 
    } 
}()); 

WindowManager= { 
    window: new Window(10, 20) 
}; 

這種模式被稱爲Immediately-invoked function expression,它是用於隱藏外部範圍的變量。這樣DEFAULT_X和DEFAULT_Y只在Window構造函數中可見。

而且this.x = xPos || WindowManager.Window.DEFAULT_X;如果xPos0然後this.x將採取默認值時,它通常是最好手動測試undefinednullif (typeof foo === "undefined" || foo === null)

0

在JavaScript中(不包括ECMAScript 6),構造函數對象定義。要使用與靜態屬性等效的東西,可以將這些附加到函數本身,而不是函數的prototype屬性。在你的情況下,它可能是這個樣子:

var WindowManager = {}; 
// Define the Window object. 
// NOTE: This function has a bug, because if DEFAULT_X and DEFAULT_Y 
// are not zero, then it will be impossible to set a window to (0,0). 
// I have kept the code as-is, to show how it corresponds to the example 
// you provided. 

function Window(xPos, yPos) { 
    this.xPos = xPos || Window.DEFAULT_X; 
    this.yPos = yPos || Window.DEFAULT_Y; 
} 

// Static properties of Window. 
Window.DEFAULT_X = 0; 
Window.DEFAULT_Y = 0; 

WindowManager.Window = Window; 

的ECMAScript 6將有所改變這種狀況,通過引入類定義語法。但目前定義的語法基本上就是我上面所做的糖。 ECMAScript 6仍然定義了一個像這樣的構造函數,非靜態成員轉到該函數的prototype屬性,靜態成員仍然成爲該函數的屬性,依此類推。