2012-02-11 93 views
1

我有一個名爲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? 
      } 
      } 

     }    
    }; 

藉口愚蠢的代碼,只是想表明我的問題。

如何結構這一點,或者說重建,在最適當的乾淨方式

回答

0

對象之間沒有內在的永久關係,它們恰好以您描述的方式定義。換句話說,爲屬性「遊戲」定義的對象與「應用程序」對象本質上不相關,並且「實例」也不與「遊戲」相關。如果你想要它,你必須明確地給它一個關聯它的屬性。

var App= { 


    aplicationFunction: function() { 
     alert("Hello, yes this is application..."); 
    }, 

    app: this, 

    getGameObj: function() { 
     var _that = this; 
     return { 

      that: _that, 

      parentF: function() { 
       this.that.aplicationFunction(); 
      }, 
     }; 
    }, 
}; 

App.getGameObj().parentF(); 

現場演示:

var Application = { 
    // ... 
    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, 
     app: null, 

     //dummy function 
     pause: function() { 
      this.app.pause(); //works, but I have to start with the "root" object, Application - how to avoid this? 
     } 
     } 

// ... 

Application.Game.instance.app = Application; 
相關問題