我有一個名爲Application
的「主」對象,它將存儲與此特定腳本相關的所有函數。 該對象中有一些各種功能,例如,start()
和pause()
,它們與子對象進行交互。如何正確地與對象內的父函數/對象進行交互
當從一個子對象(應用程序對象,甚至更深)調用這些函數時,我必須直接參考Application.function()
。其中可以得到非常clutty。如果我需要與子數據this.Game.instance.sessionId
進行交互,這些功能就是這種情況。它會失敗,如果隨着我的需求增長,未來添加更多對象會怎樣?它會變得非常混亂,更不用說冗長了,只是爲了與另一個孩子/父母對象進行交互。
示例代碼:
var Application = {
//Start the whole application
start: function() {
doSomething(this.Game.instance) //do something with the game instance object
},
pause: function() {
//pause the current sessionId
interactWithMyServer(this.Game.instance.sessionId); //clutty
}
Game: {
//redraw the game to reflect changes
redraw: function() {
someDrawFunction(this.instance); //draw the instance
},
//Stores information about the game instance from the server, changes often
//bad example with the pause, but just to get the idea of my example
instance: {
gameId: 23,
sessionId: 32,
map: 32,
//dummy function
pause: function() {
Application.pause(); //works, but I have to start with the "root" object, Application - how to avoid this?
}
}
}
};
藉口愚蠢的代碼,只是想表明我的問題。
如何結構這一點,或者說重建,在最適當的和乾淨方式?