2017-01-25 39 views
0

目前,我正在做一個小遊戲結構類似這樣:的Javascript - 閉幕遇事調用外部函數時

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(); 

的想法是通過調用函數Graphics()Graphics標識碼從內部代碼分開方法(所以我可以例如在單獨的文件中構建Graphics()函數)。但是,當我這樣做時,Graphics方法會丟失我在開始時聲明並在init方法中分配的私有變量,並在Graphics中的某種方法調用Uncaught ReferenceError: private is not defined時拋出該變量。

我想一個解決方案只是重新分配在Graphics()這些私人,但這會有點殺死的目的。任何人有更好的主意?提前致謝。

編輯:使代碼更容易一點了解我在

+0

這不是我清楚什麼是你的實際問題。有沒有像你期望的那樣工作?如果是這樣,請提供一個可重現的例子。 – abl

+0

上面給出的代碼片段是語法錯誤的。請糾正這一點。 – alicanerdogan

回答

0

越來越如果你想私有變量您的顯卡類型不應該訪問它們。如何聲明公共變量呢?

像這樣的實例:

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

或者你可以聲明干將進入私人領域,並通過遊戲實例的顯卡類型。像這樣:

let Game = function() { 

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

} 

function Graphics(game) { 

    // ... 

} 
0

我認爲你正在嘗試使用O.O.在JavaScript中。 Javascript是原型,所以,你將使用O.O.的方式。與通常的語言不同。 see mozilla reference

我想你應該創建JS類這樣的:

/** 
* @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();