2012-02-11 3 views
1

Application이라는 "주"개체가 있는데이 개체는이 특정 스크립트와 관련된 모든 기능을 저장합니다. 해당 개체에는 몇 가지 다양한 기능이 있습니다 (예 : start()pause()).이 개체는 하위 개체와 상호 작용합니다.개체 내부의 부모 함수/개체와 올바르게 상호 작용하는 방법

이러한 기능을 Application 개체의 자식 개체 (또는 더 심층적 인 개체)에서 호출 할 때는 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; 
0

일부 폐쇄 방법을 정의하여 부모에 대한 참조를 전달할 수 있습니다

gameobj = App.getGameObj(); 
gameobj.parentF(); 
자세한 편의를 위해 http://jsfiddle.net/vZDr2/

을 당신은 다음 예제로 사용할 수 있습니다

관련 문제