2017-01-25 2 views
0
나는 현재 작은 게임을 만들고있어

은과 같이 구성 실패 :자바 스크립트 - 외부 함수를 호출 할 때 폐쇄는

let Game = function() { 

    let privateVar; 
    // private would be an example private variable assigned later 
    // Other private variables go here 

    return { 
     Engine: function() { 

      // More specific private variables 

      init: function() { 
       privateVar = this.sampleValue; 
       // Game.Engine.sampleValue doesn't help either 

       // Start up everything, for example, calling a Graphics method: 
       Game.Graphics.method1(); 
      }, 

      sampleValue: 10, 

      // Other methods 
     } 

     Graphics: Graphics() 
    } 
} 

function Graphics() { 

    // Visuals-specific private variables 

    return { 

     method1: function() { 
      console.log(privateVar); 
      // This would complain about the variable not being defined 
     } 

     // methods 

    } 
} 

Game.Engine.Init(); 

아이디어는 GraphicsGraphics() 함수를 호출하여 내부 코드에서 시각적 코드를 분리하는 것입니다 메서드 (예를 들어, Graphics() 함수를 별도의 파일로 빌드 할 수 있습니다). 그러나 이것을 수행 할 때 Graphics 메서드는 내가 처음 선언 한 private 변수를 잃어 init 메서드에서 할당되고 Graphics의 메서드에 의해 호출 될 때마다 Uncaught ReferenceError: private is not defined을 출력합니다.

나는 한 솔루션이 단지 Graphics()에있는 해당 개인을 재 할당하는 것 같지만, 그 목적은 다소 어긋납니다. 누구나 더 좋은 아이디어가 있습니까? 미리 감사드립니다.

편집 : 당신이 private 변수는 사용자의 그래픽 유형에 액세스하지 않아야합니다 내가

+0

see mozilla reference

나는 당신이이 같은 JS 클래스를 생성해야한다고 생각 실제 질문. 기대했던 것처럼 작동하지 않는 것이 있습니까? 그렇다면 재현 가능한 예를 제공해주십시오. – abl

+0

위에 제시된 코드 스 니펫은 구문 적으로 잘못되었습니다. 그것을 수정하십시오. – alicanerdogan

답변

0

에서 얻고 이해하는 것이 조금 더 쉽게 코드를 제작. 공개 변수를 선언하는 것은 어떨까요? 예를 들어이 같이

:

let Game = function() { 
    this.publicVar = "value"; 
} 

아니면 private 필드에 액세스하고 그래픽 형식으로 게임 인스턴스를 전달하는 게터를 선언 할 수 있습니다. 이와 같이 :

let Game = function() { 

    let privateVar = "value"; 
    this.getPrivateVar = function() { 
     return privateVar; 
    } 

} 

function Graphics(game) { 

    // ... 

} 
0

나는 당신이 O.O.를 사용하려한다고 생각한다. 자바 스크립트. 자바 스크립트가 프로토 타입이므로 O.O. 는 일반적인 언어와 다릅니다.

/** 
* @class Game Class 
*/ 
function Game() { 

    this.privateProperty; 

    this.engine = new Engine(); //engine object of this game 
    this.graphics = new Graphics(); //graphics object of this game 
} 

Game.prototype.oneGameMethod = function(){ 

}; 


/** 
* @class Engine Class 
*/ 
function Engine(){ 
    this.privateProperty; 

} 

Engine.prototype.oneEngineMethod = function(){ 

}; 


/** 
* @class Graphics class 
*/ 
function Graphics() { 

    // Visuals-specific private variables 
    this.visualProperty; 
} 
Graphics.prototype.oneMethodExample = function(){ 

}; 

을 그렇게에서 게임 객체를 생성하고 메소드를 호출 할 수 있습니다보다 : 그것은 당신의 무엇을 나에게 분명하지 않다

var myGame = new Game(); 
관련 문제